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