tags:

views:

37

answers:

2

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);
+6  A: 
var reg = new Regex(@"\b" + currentKeyword + @"\b", ...);

The \b means a word boundary.

KennyTM
Thanks for your answer. I marked wRAR as the correct answer as he was the first to post, but your explanation is the best one.
pablo
+1  A: 

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

wRAR