开发者

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" />开发者_JAVA技巧;

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!


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.


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

Set the value of the Int32 to 1.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜