Replacing only full words in a string with Regex
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"
.
精彩评论