(?<!a)b?c
Against abc
, this regex matches c
. Am I missing something?
Yes, that is correct. Here is a quick walk-through of the match from the engine's stand point.
a
. Fail. Advance in the string.a
. Fail. Advance in the string.c
(?<!a)
assert that what precedes is not a
? Check. (It's b
)b?
match zero or one b
? Check. We match zero b
c
matches a c
? Check. Looking Far Behind
In .NET, which has infinite lookbehind, you could use this:
(?<!a.*)b?c
But PCRE does not have infinite lookbehind. You can use this instead:
^[^a]*\Kb?c
How it works:
^
anchor asserts that we are at the beginning of the string[^a]*
matches any non-a chars\K
tells the engine to drop what was matched so far from the final match it returnsb?c
matches the optional b
and the c