Looping Regex with Replace

Viewed 82

In C#, I'm working with a small text file of variable length (it may have 4-6 lines).

Each line contains a repeating expression, followed by a 2-digit number and a colon and some concluding information.

For example:

some information 27: some other information
some information 28: some other information
some information 29: some other information

I need to remove all the characters up to and including the colon ':', leaving just the concluding information.

I have tried using a Regex expression as shown below. It correctly handles the first line in the file, but only the first line.

private static string ModifyTheInformation(string str)
{
    string pattern = "^[^:\r\n]+:[ \t]*";
    string replacement = "";

    if (Regex.IsMatch(str, pattern, RegexOptions.Multiline))
    {
        str = Regex.Replace(str, pattern, replacement);
    }
}

I need the Regex to loop through the file and affect all the lines. I have also tried using the Regex Match match method and match.NextMatch. For example:

Regex r = new Regex(pattern, RegexOptions.Multiline);
Match m = r.Match(str);
while (m.Success)
{
    //try something
}

However, an instance variable does not offer the 'Replace' method.

Please suggest how I may use a Regex expression, which both Loops and can Replace the specified characters in each line of a text file.

2 Answers

You omitted RegexOptions.Multiline in the call to Regex.Replace, but kept it in the Regex.IsMatch call, that is your mistake.

You do not need to check for a regex match with the Regex.IsMatch because Regex.Replace returns the unchanged string if no matches were detected.

Use

private static string ModifyTheInformation(string str)
{
    return Regex.Replace(str, "^[^:\r\n]+:[ \t]*", "", RegexOptions.Multiline);
}

See the regex demo.

However, it seems all you need is to read the input file line by line and remove all before the first colon with a mere

line.Substring(line.IndexOf(":") + 1).Trim()

See the C# demo.

You really don't need a regex here - simply split each line of text on ':', e.g.

    string x = "some information 27: some other information";
    Console.WriteLine(x.Split(new char[]{':'}, 2)[1]);
Related