user827098
user827098

Reputation: 77

regex to replace a word if it doesn't have specific one before

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

Answers (3)

Colonel Panic
Colonel Panic

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

  1. Replace "Ballmer" with "Steve Ballmer"
  2. Replace "Steve Steve Ballmer" with "Steve Ballmer" (to correct for any oversteving)

Alternatively

  1. Replace "Steve Ballmer" with "Ballmer"
  2. Replace "Ballmer" with "Steve Ballmer"

Upvotes: 0

Ωmega
Ωmega

Reputation: 43673

Use negative lookbehind (?<!...) and positive lookahead (?=...)

string output = Regex.Replace(input, @"(?<!Steve )(?=Ballmer)", "Steve ");

Upvotes: 4

Martin Ender
Martin Ender

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

Related Questions