What will be the regular expression to match a word if its not in the start of the string? For example, for United to be matched, the string should be "We are United on it". It should not be matched for "United States". I used expression \w+\s+(United) but it returns are United when matching. I just want United to be matched.
What expression I’ll be using? And, as I’ll replace the matched expression, do I need a loop for replacing multiple occurrences?
Following is some part of the code:
var s = "We are United on it.";
var regex = new Regex(@"\w+\s+(United)", RegexOptions.IgnoreCase);
if (regex.IsMatch(s))
{
returnString = Regex.Replace(s,@"\w+\s+(United)" , "xyz");
}
Any code example will be greatly helpful. Thanks!
In general, when you want to impose a condition on what is next to a match, but not include that text in the match, you need an assertion, for example one of
In this case we want to assert something about what comes just before the match, so we need a look-behind assertion. And since what we want to assert is: “just before the match, don’t have the start of the string”, we need a negative look-behind assertion:
The syntax for a look-behind negative assertion is
(?<!text), replacingtextwith whatever you are saying should not appear just before the match.As an additional point, you don’t really need to separately call
.IsMatchand.Replace–.Replacewill simply do nothing if there is no match.And you don’t need a loop –
.Replacewill replace all matches, unless you take specifically call the overload that limits the number of replacements.