正则表达式只匹配一次

时间:2012-12-20 18:06:00

标签: c# regex

我有文字

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

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

2 个答案:

答案 0 :(得分:1)

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

因此,在正则表达式(abc)(def)中,第一个组为abc,第二个组为def

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

答案 1 :(得分: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:00:03,837 - &gt; 00:00:07170
  文本1

     

00:00:08,875 - &gt; 00:00:10,968
  TEX2

     <00> 00:00:11,010 - &gt; 00:00:13843个
  文本3