Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I find Regex Matches in an array including repeats in C#

I have a method in C# that uses Regex to find any strings that match any {{word:word}} pattern:

private string ModifyVariables(string text) {
    String pattern = @"{{([\w|]+:\w+)}}";
    MatchCollection matches = Regex.Matches(text, pattern);

    for (int i = 0; i < matches.Count; i++) {
        Match match = Regex.Match(text, pattern);

        string value = GetVariableValue(match.Value);

        text = text.Replace(match.Value, value);
    }

    return text;
}

The problem is that MatchCollection is a set and therefore does not include repeats. If there is another string that matches the regex and has the exact same string, then it will not change MatchCollection.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Are you looking for Regex.Replace?

private string ModifyVariables(string text) => Regex
  .Replace(text, @"{{([\w|]+:\w+)}}", match => GetVariableValue(match.Value));

Here for each variable found (match) we change the match (variable usage) with variable’s value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading