Regular expression to match A, AB, ABC, but not AC. (“starts with”)

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.).

Leave a Comment