32

It seems the .NET Regex.Replace method automatically replaces all matching occurrences. I could provide a MatchEvaluator delegate that returns the matched string after the first replacement, rendering no change, but that sounds very inefficient to me.

What is the most efficient way to stop after the first replacement?

Shane Fulmer
  • 7,510
  • 6
  • 35
  • 43
spoulson
  • 21,335
  • 15
  • 77
  • 102

4 Answers4

32

From MSDN:

Replace(String, String, Int32)   

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

Isn't this what you want?

bzlm
  • 9,626
  • 6
  • 65
  • 92
28

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

(?<!foo.*)foo

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

5

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

Viktor Pless
  • 161
  • 1
  • 12
4

In that case you can't use:

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

Instead you need to declare new Regex instance and use it 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 number of occurrences the replacement should occur.

Pini Cheyni
  • 5,073
  • 2
  • 40
  • 58