[ACCEPTED]-How to Regex search/replace only first occurrence in a string in .NET?-regex

Accepted answer
Score: 31

From MSDN:

Replace(String, String, Int32)   

Within a specified input string, replaces 4 a specified maximum number of strings that 3 match a regular expression pattern with 2 a specified replacement string.

Isn't this 1 what you want?

Score: 27

Just to answer the original question... The 4 following regex matches only the first instance 3 of the word foo:

(?<!foo.*)foo

This regex uses the negative 2 lookbehind (?<!) to ensure no instance 1 of foo is found prior to the one being matched.

Score: 4

You were probably using the static method. There 3 is no (String, String, Int32) overload for 2 that. Construct a regex object first and 1 use myRegex.Replace.

Score: 2

In that case you can't use:

string str ="abc546_$defg";
str = Regex.Replace(str,"[^A-Za-z0-9]", "");

Instead you need 4 to declare new Regex instance and use it 3 like this:

string str ="abc546_$defg";
Regex regx = new Regex("[^A-Za-z0-9]");
str = regx.Replace(str,"",1)

Notice the 1, It represents the 2 number of occurrences the replacement should 1 occur.

More Related questions