Is it true C#.NET has no "global flag" for regular expressions?

Many regular expression systems, such as the one for JavaScript, require some kind of "global flag" for a pattern to be matched everywhere  (e.g., the regular expression /xyz/g means match "xyz" throughout the target string). Otherwise the match is made only once. Thus for a replacement, all occurrences of the match are replaced (the "g" case) or only the first one (the default case).

C#.NET doesn't seem to have a "global flag". Is this correct -- the default behavior is match every occurrence? And if so, how would you specify to match (e.g., replace) only the first occurrence?
Who is Participating?
Fernando SotoConnect With a Mentor RetiredCommented:
Hi roricka;

To your question, "C#.NET doesn't seem to have a "global flag". Is this correct", as far as regular expression it does not have a global flag.

using System.Text.RegularExpressions;

String TestStr = "1: This is line 1 2: This is line 2 3: This is line 3";
String pattern = @"\d:[^\d]+\d";

// Returns the first match found and stops
Match test1 = Regex.Match(TestStr, pattern);

Console.WriteLine(test1.Value + "\n");

// This will return a all/globel match, note we use the regex Matches method here
MatchCollection test2 = Regex.Matches(TestStr, pattern);

foreach (Match m in test2)

To the question, "the default behavior is match every occurrence?", No it depends on wich method you use, Match returns the first and Matches returns all.

To the second part to the above question, "And if so, how would you specify to match (e.g., replace) only the first occurrence?", can you give an example of what you want to do.

rorickaAuthor Commented:
You pointed me in the right direction. I should have asked how to have Replace only replace the first occurrence. I see that Replace is overloaded. By default it replaces all matches, but it is possible to specify the number of replacements (including just 1).

Javascript's approach is clearly less sophisticated, but it was confusing, since in that system the global specifier is given with the regular expression, not implied as an argument to "replace" (note: lower-case "r" for Javascript.)

Anyway, thanks. I marked the solution was "partially" complete more because of my poorly worded question than any fault on your part.
Fernando SotoRetiredCommented:
Not a problem, glad I was able to get you pointed in the right direction. Have a great day  ;=)
All Courses

From novice to tech pro — start learning today.