Friday, 22 July 2016

c# - Replacing only full words in a string with Regex



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



Part of the problem is solved, but I need to replace only full words, and 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:



var reg = new Regex(currentKeyword, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Multiline);

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

Answer



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


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...