.net – How to Regex search/replace only first occurrence in a string in .NET


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?

Best Solution

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?