I have situation where in the regular expression is something like this:
^b?A+b?$
So b
may match at the start of the string 0 or 1 times, and A
must match one or more times. Again b
may match at the end of the string 0 or 1 times.
Now I want to modify this regular expression in such way that it may match b
either at the start or at the end of the string, but not both.
How do I do this?
Theres a nice "or" operator in regexps you can use.
^(b?A+|A+b?)$
Try this:
^(bA+|A+b?)$
This allows a b
at the start and then at least one A
, or some A
s at the start and optionally a b
at the end. This covers all the possibilities and is slightly faster than the accepted answer in the case that it doesn't match as only one of the two options needs to be tested (assuming A
cannot begin with b
).
Just to be different from the other answers here, if the expression A is quite complex but b is simple, then you might want to do it using a negative lookahead to avoid repeating the entire expression for A
in your regular expression:
^(b(?!.*b$))?A+b?$
The second might be more readable if your A is complex, but if performance is an issue I'd recommend the first method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With