Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 664
Jenni Avatar asked Jan 05 '10 16:01

Jenni


1 Answers

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

like image 59
Gumbo Avatar answered Nov 01 '22 21:11

Gumbo