I got a "little" problem already... I only want to replace some names with other names or something. It works fine so far, but with some names I got a problem.
For example I want to replace "Cho"
with "Cho'Gath"
, but of course I don't want to replace "Cho'Gath"
with "Cho'Gath'Gath"
.
So therefore I created this regular expression, and replace all "Cho"
's except of "Cho'Gath"
:
/\bCho(?!.+Gath)\b/i
This works and it doesn't replace "Cho'Gath"
, but it also doesn't replace "Cho Hello World Gath"
... that is my first problem!
The second one is follwing: I also want to replace all "Yi"
, but not "Master Yi"
, so I tried the same with the following regular expression:
/\b(?!Master.+)Yi\b/i
This doesn't replace "Master Yi"
, okay. But it also doesn't replace "Yi"
, but it should do! (I also tried /\b(?!Master(**\s**))Yi\b/i
but this also doesn't work)
So far I don't know what to do know... can anyone help me with that?
Your first problem is easily solved if you replace .+
with the actual character that you want to match (or not to match): '
, but let's have a look at the second one, this is quite interesting:
I also want to replace all "Yi", but not "Master Yi", so I tried the same with the following regular expression:
/\b(?!Master.+)Yi\b/i
This is a negative lookahead on \b
. The expression does match a single "Yi", but look what it does with "Master Yi":
Hello I am Master Yi
^
\b
This boundary is not followed by "Master" but followed by "Yi". So your expression also matches the "Yi" in this string.
The negative lookahead is quite pointless because it checks if the boundary that is directly followed by "Yi" (remember that a lookahead assertion just "looks ahead" without moving the pointer forward) is not directly followed by "Master". This is always the case.
You could use a lookbehind assertion instead, but only without the (anyways unnecessary) .+
, because lookbehind assertions must have fixed lengths:
/\b(?<!Master )Yi\b/i
matches every "Yi" that is not preceded by "Master ".
For the first regex:
\bCho(?!.Gath)\b
For the second:
(?<!\bMaster )Yi\b
Your first regex had .+
in it, that is one character, one or more times; and as quantifiers are greedy by default, this swallows the whole input before reluctantly giving back to match the next token (G
).
Your second regex used a negative lookahead, what you wanted was a negative lookbehind. That is, a position where the text before that position does not match.
And note that regexes in lookbehinds must be of finite length.