0

我有文字

1
00:00:03,837 --> 00:00:07,170
Text1

2
00:00:08,875 --> 00:00:10,968
Tex2

3
00:00:11,010 --> 00:00:13,843
Text3

我想让它像那样

00:00:03,837 --> 00:00:07,170
Text1

00:00:08,875 --> 00:00:10,968
Tex2

00:00:11,010 --> 00:00:13,843
Text3

我试过这个:

Match match = Regex.Match(loadedText, @"\d{1,4}\r\n");

if (match.Success)
{
    for (int i = 0; i < match.Groups.Count; i++)
    {
        loadedText= loadedText.Replace(match.Groups[i].Value, "");
    }
    rtbLoaded.Text = loadedText;
}

但它给了我这个结果:

00:00:03,837 --> 00:00:07,170
Text1

2
00:00:08,875 --> 00:00:10,968
Tex2

3
00:00:11,010 --> 00:00:13,843
Text3

所以只有一次......我做错了什么?

4

2 回答 2

1

试试这个替换规则:

string result = Regex.Replace(originalString, @"(?<=(\r\n|^))(\d+\r\n)", "");

这将替换所有仅包含数字的行或第一行中包含数字的行。

参考您的示例输入:

string input = "1\r\n00:00:03,837 --> 00:00:07,170\r\nText1\r\n\r\n2\r\n00:00:08,875 --> 00:00:10,968\r\nTex2\r\n\r\n3\r\n00:00:11,010 --> 00:00:13,843\r\nText3\r\n\r\n";
Console.WriteLine(Regex.Replace(input, @"(?<=(\r\n|^))(\d+\r\n)", ""));

这输出:

00:00:03,837 --> 00:00:07,170 文本
1

00:00:08,875 --> 00:00:10,968
Tex2

00:00:11,010 --> 00:00:13,843 文本
3

于 2012-12-20T18:09:47.020 回答
1

组是正则 ()表达式中的部分,而不是单个匹配项。

所以在正则表达式(abc)(def)中,第一组是abc,第二组是def

不要遍历(您只有默认组!),您需要匹配多次。也许使用内置的替换方法而不是Replace你在那里做的这个黑客。

于 2012-12-20T18:09:28.527 回答