Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: How to optionally match something at beginning or end, but not both?

Tags:

regex

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?

like image 747
coder_bro Avatar asked Oct 19 '25 04:10

coder_bro


2 Answers

Theres a nice "or" operator in regexps you can use.

^(b?A+|A+b?)$
like image 175
Dietrich Epp Avatar answered Oct 21 '25 17:10

Dietrich Epp


Try this:

^(bA+|A+b?)$

This allows a b at the start and then at least one A, or some As 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.

like image 21
Mark Byers Avatar answered Oct 21 '25 17:10

Mark Byers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!