tags:

views:

1983

answers:

3

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?

+10  A: 

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
Wow, how did I miss that? Thanks for the tip.
spoulson
A: 

There's a related, essentially duplicate question here.

I do agree with bzlm, though - that's the answer.

itsmatt
+2  A: 

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.

Will