a1204773
a1204773

Reputation: 7043

Regex matching only once

I have text

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

And I want to make it like that

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

I tried this:

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;
}

Bu it give me this result:

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

So it much only once... What I do wrong?

Upvotes: 0

Views: 1447

Answers (2)

rekire
rekire

Reputation: 47945

Try this replace rule:

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

This will replace all lines with only numbers or a line with a number in the first line.

Refering to your example input:

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)", ""));

This outputs:

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

Upvotes: 1

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

Groups are the parts in () in a regexp, not the individual matches.

So in the regexp (abc)(def) the first group is abc, the second group is def.

Don't iterate over the groups (you only have the default group!), you need to match multiple times. Maybe use a built in replacement method instead of this Replace hack that you are doing there.

Upvotes: 1

Related Questions