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

后端 未结 4 1312
被撕碎了的回忆
被撕碎了的回忆 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:09

    This seems a little extravagant, but it works for character classes as well as characters.

    (You would always use indexOf if it could be expressed as a string.)

    You used to be able to edit a RegExp, but now you need a new one with any change.

    RegExp.prototype.extend= function(c){
     var s= '', rx= this.toString();
     rx= rx.replace(/(\W+)$/, c+'$1').replace(/^\/|\/$/g,'');
     if(this.global) s+= 'g';
     if(this.multiline) s+= 'm';
     if(this.ignoreCase) s+= 'i';
     return RegExp(rx, s);
    }
    
    String.prototype.longMatch= function(arr){
     // if(this=='') return true;
     var Rx= RegExp("^("+arr.shift()+")");
     var i= 0, L= Math.min(s.length, arr.length),
     M= this.match(Rx);
     while(i< L){
      if(!M) return false;
      Rx= Rx.extend(arr[i++]);
      M= this.match(Rx);
     }
     return M[0]==this;
    }
    
    var arr= ['A','B','C','D'];
    var s= 'ABCD';// try various strings
    alert(s.longMatch(arr));
    
    0 讨论(0)
  • 2020-12-02 01:26
    /^A(?:B(?:C)?)?$/
    

    should do it.

    This is using the non-capturing group construct (?: xxx ) so as not to mess up any match capturing you may be doing.

    0 讨论(0)
  • 2020-12-02 01:26

    This should do it:

    /^A(BC?)?$/
    
    0 讨论(0)
  • 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.).

    0 讨论(0)
提交回复
热议问题