Ian Davis
Ian Davis

Reputation: 19413

How to replace 1st match of regex pattern, leave others alone

With C#, how do I replace only the first match of something?

Example input: <img src="1.jpg" />some other text<img src="2.jpg" />

Regex I'm using, which works: <img.*?>

The following replaces all matches, but, I just want to replace the first one and leave the 2nd one (and all others) alone.

string val = Regex.Replace(input, "<img.*?>", string.Empty);
return val;

Thanks!

Upvotes: 1

Views: 1410

Answers (2)

David
David

Reputation: 73554

Use the overloaded Regex.Replace Method (String, MatchEvaluator, Int32)

Set the value of the Int32 to 1.

Upvotes: 2

SLaks
SLaks

Reputation: 887305

Pass 1 as the third parameter.

Regex.Replace has an overload that takes a maximum number of replacements to make.


Note that you can achieve substantially better performance by putting a Regex instance in a static readonly field. This way, the runtime won't need to re-parse the regex every time you call Replace.

Upvotes: 3

Related Questions