The statement
Regex.Replace(\"XB\", \"([^A])B\", \"$1AB\")
produces XAB
, as expected. Can someone explain me why
R
Note that this ([^A])B
regex matches the first XB
and captures the X
. Because the B
following the X
is already present in a match, so it won't be matched another time. In this case, i suggest you to use lookarounds.
([^A])(?=B)
(?=B)
Positive lookahead which asserts that the match must be followed by the letter B
.
But it produces XABBABB
when the replacement string is $1AB
. To get the desired output, just remove the B
from the replacement string. That is replace the matched characters with \1A
DEMO
In a .NET regex flavor, you may use lookbehinds like this:
Match foo
not immediately preceded with bar
(?<!bar)foo
See the regex demo.
Match foo
not preceded with bar
anywhere in the string
(?s)(?<!bar.*?)foo
See the regex demo.
Match foo
immediately preceded with bar
(?<=bar)foo
See the regex demo.
Match foo
preceded with bar
anywhere in the string
(?s)(?<=bar.*?)foo
See the regex demo.
The latter contains .*?
in the negative lookbehind allowing the regex engine to check for bar
and any zero or more chars immediately to the left of foo
, so the bar
does not have to come immediately before foo
.
The (?s)
inline modifier allows .
to match any characters including newlines.
The current problem is easily solved by using a negative lookbehind (see the top scenario),
var result = Regex.Replace("XBB", "(?<!A)B", "AB");
All B's not preceded by a A by AB.
Find: (?<!A)B
Replace: AB