我有文字
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
所以这只是一次......我做错了什么?
答案 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
文本100:00:08,875 - &gt; 00:00:10,968
<00> 00:00:11,010 - &gt; 00:00:13843个
TEX2
文本3