Regular expression for matching A, AB, ABC, but not AC. ( "begin with" )

I bang my head against the wall. I want a regular expression that matches the empty string, A, ABand ABC, but not AC. I have this one that works:

/^(A|AB|ABC)?$/

But this is a simplification; in my application A, Band Care actually long character classes, so I don’t want to repeat them again and again. Maybe I'm just not looking at it right. I tried this:

/^((AB?)C?)?$/

But it is still consistent AC.

Is there an easier way to do this, which can be extended up to (say) ABCD, ABCDEetc.?

Change . Expanding to ABCDE, I mean that it will match an empty string, A, AB, ABC, ABCD, ABCDE. Basically, it starts with a regular expression.

+3
source share
4 answers

Try this regex:

^(A(B(C)?)?)?$

I think you can see the template and expand it for ABCDand ABCDEhow:

^(A(B(C(D)?)?)?)?$
^(A(B(C(D(E)?)?)?)?)?$

Now each part depends on the preceding parts (B depends on A, C depends on B, etc.).

+9
source

This should do it:

/^A(BC?)?$/
+4
source
/^A(?:B(?:C)?)?$/

.

(?: xxx ), , .

+4

This seems a little extravagant, but it works for both character classes and characters.

(You will always use indexOf if it can be expressed as a string.)

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

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
source

Source: https://habr.com/ru/post/1727377/


All Articles