Disabling Global for Regex

I want to turn off the Global setting (as it is set default to be used on .NET) as what I am trying to do only needs to change the first part of a string, however there is the the chance that it will occur twice in the string, for example I wish for


to only change the first instance of 0's.

if (Regex.IsMatch(text, "^[a-z]+00+", RegexOptions.IgnoreCase))
    text = Regex.Replace(text, "0{1,}", "00*", RegexOptions.IgnoreCase);

This is how I am currently doing it, however this seems to take every single instance of the "00+" and change it but this messes things up.


You need to specify a match limit; the documentation for Regex.Replace(string, string, RegexOptions) specifically states that it replaces all instances of the found pattern. There is no static overload of Regex.Replace that takes both a match limit and regex options, so you will have to construct a Regex object and then use the Replace(string, string, int) overload. Try this:

text = new Regex("0{1,}", RegexOptions.IgnoreCase).Replace(text, "00*", 1);

You could alter your regex slightly so that it matches the intended pattern and only replaces the first set of zeroes. That also helps cut out the IsMatch call.

The pattern you can use is: (?<=^[a-z]+)00+

This pattern is similar to your first one, except it uses a look-behind, (?<=^[a-z]+), to ensure that the match occurs as intended at the beginning of the string with letters. The usage of a look-behind will match, but not consume, so the replace won't affect that portion of the string.

string text = "C00000WPF0000SAND";
text = Regex.Replace(text, "(?<=^[a-z]+)00+", "00*", RegexOptions.IgnoreCase);

Another solution is:

text = Regex.Replace(text, "(?i)^([a-z]+)00+", "${1}00*");

In which case you don't need the if at all.

Need Your Help

How to refresh external Jars in Eclipse project (Java)?

java eclipse jar project refresh

I have a Java project in Eclipse which includes a couple of external jar files. These external jar files are being rebuilt through a different process (not Eclipse, Ant). Those changes are not being

Export HTML and CSS from Photoshop or InDesign

html css dreamweaver photoshop adobe-indesign

I am building web site and I've got .psd file of how the site should look like and I can make it manually but it will take time. I was wondering if there is a way to export a Photoshop or InDesign ...