开发者

Replacing only full words in a string with Regex

开发者 https://www.devze.com 2022-12-22 05:58 出处:网络
I want to replace only the first occurrence of a word in a sentence with regex. I want to replace only full words, and therefore exclude partial matches.

I want to replace only the first occurrence of a word in a sentence with regex.

I want to replace only full words, and therefore exclude partial matches.

For example, in the sentence "The quick brown foxy fox jumps over the lazy dog", I would like to replace fox by cat.

The result that I could achieve was the following: "The quick brown caty fox jumps over the lazy dog". As opposed to foxy cat.

I am using the Regex.Replace method as follows:

v开发者_开发百科ar reg = new Regex(currentKeyword, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);

reg.Replace(input, replace, 1, 0);


var reg = new Regex(@"\b" + currentKeyword + @"\b", ...);

The \b means a word boundary.


Use a correct regex, such as @"\bcat\b".

0

精彩评论

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

关注公众号