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

后端 未结 4 1354
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 00:40

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,

4条回答
  •  星月不相逢
    2020-12-02 01:31

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

提交回复
热议问题