Regular Expression problem: how to determine that there's no B between A and C?
I need an regular expression that matches A.*C
only if there's no "B" in between. Before and after "A.*C
without B in between", any string is allowed (including A, B and C).
I think I need a .*
somewhere between A and B, so I tried (amongst others) these two:
A.*(?!B).*C
doesn't work, as the .*
after A "eats" the B.
A(?!.*B).*C
doesn't work, as it doesn't match ACB
. (This time, the first .*
"eats" the "C").开发者_JAVA技巧
Possibly I'm missing something obvious - I can't figure out how to do it.
Thanks for the help, Julian
(Edit: having some formatting troubles...)
The easiest way to achieve this is using lookarounds:
A((?!B).)*C
This pattern will match A
, then any number of characters, and then C
. However, because of the negative lookahead on the .
, the dot will only match if it isn't going to consume B
.
How about A[^B]*C
?
[^B]
is a character class matching "anything but the letter 'B'".
Why not /A(?!.*B.*(C)).*?C/
?
How about this:
\AA.+(?<!(.*cheesey.*))C\Z
The (?<!(.*cheesey.*))
does a negative lookbehind for the pattern .*cheesey.*
and stops matching if it finds a match. The anchors are there to stop it from chopping off the end and matching in the middle even though 'cheesey' might be at the end.
"A[^B]*C". Matches an A, then any number of characters that isn't B, then C.
精彩评论