I'm banging my head against a wall. I want a regex that matches: empty string, A, AB, and ABC, but not AC. I have this, which works:
/^(A|AB|ABC)?$/
But this is a simplification; in my app A, B, and C are actually long character classes, so I don't want to repeat them over and over. Maybe I'm just not looking at it the right way. I tried this:
/^((AB?)C?)?$/
But that still matches AC.
Is there a simpler way to do this, that could be extended to (say), ABCD, ABCDE, etc.?
Edit: By extend to ABCDE, I mean it would match: empty string, A, AB, ABC, ABCD, ABCDE. Basically, a "starts with" regex.
Try this regular expression:
^(A(B(C)?)?)?$
I think you can see the pattern and expand it for ABCD and ABCDE like:
^(A(B(C(D)?)?)?)?$
^(A(B(C(D(E)?)?)?)?)?$
Now each part depends on the preceeding parts (B depends on A, C depends on B, etc.).
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