42

Possible Duplicate:
How to Regex search/replace only first occurrence in a string in .NET?

How do I make Regex.Replace replace only the first found pattern?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Luke
  • 5,771
  • 12
  • 55
  • 77

2 Answers2

74

What about Regex.Replace ( String, String, Int32 ) (MSDN) ?

An example:

Regex rgx = new Regex(pattern);
string result = rgx.Replace(str, replacement, 1); // The 1 makes the difference
cimnine
  • 3,987
  • 4
  • 33
  • 49
  • what if you want to provide `count` parameter and `RegexOptions.IgnoreCase` at the same time ? I cannot find any overload that fit. – tigrou Jan 02 '17 at 10:26
  • 2
    @tigrou you provide options in the constructor `new Regex(pattern, RegexOptions.IgnoreCase)`, not in the `Replace` function. – grek40 Aug 18 '17 at 14:12
4

http://msdn.microsoft.com/en-us/library/haekbhys.aspx

you can use Regex.Replace(input, replacement, count);

kavun
  • 3,358
  • 3
  • 25
  • 45
  • 1
    You cant. you need an instance because the overloads for the statics methods require a patter also. Sorry This was nothing to do with the question. – Justin Sep 26 '17 at 01:50