Merge your two negated character classes and remove the [^A]
from the second alternation:
regex = "AB([^AB]|B|[^B]A)*BA"
This regex fails on the string ABABA
, though - not sure if that is a problem.
Explanation:
AB # Match AB
( # Group 1 (could also be non-capturing)
[^AB] # Match any character except A or B
| # or
B # Match B
| # or
[^B]A # Match any character except B, then A
)* # Repeat as needed
BA # Match BA
Since the only way to match an A
in the alternation is by matching a character except B
before it, we can safely use the simple B
as one of the alternatives.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…