Reputation: 77
Using regex in C# I should replace one word if it doesn't have specific one before In my example it to replace "Ballmer" with "Steve Ballmer"
In:
...text...Ballmer...text
Result:
...text...Steve Ballmer...text
but if "Steve" already there, I shouldn't add Steve again.
In:
...text...Steve Ballmer...text
Result:
...text...Steve Ballmer...text
Thanks.
Upvotes: 2
Views: 123
Reputation: 137574
Regular expressions are fun, but it's also worthwhile to try simpler tools before resorting to the big guns. This particular problem can be solved with basic find-and-replace
Alternatively
Upvotes: 0
Reputation: 43673
Use negative lookbehind (?<!...)
and positive lookahead (?=...)
string output = Regex.Replace(input, @"(?<!Steve )(?=Ballmer)", "Steve ");
Upvotes: 4
Reputation: 44259
Use a negative lookbehind when matching Ballmer
:
string result = Regex.Replace(input, @"(?<!Steve )Ballmer", "Steve Ballmer");
This will do exactly what you want. Match any Ballmer
that is not immediately preceded by Steve
(and a space).
Upvotes: 2