I search for a regex expression that should be either:
- BILL followed by 10 digits ( the total length should be 14 )
- AAAASPA followed by 6 digits ( the total length should be 13 )
I tried this ^(BILL\d{10}){14}|(AAAASPA\d{6}){13}$
But It does not work.
CodePudding user response:
The (BILL\d{10}){14}
matches BILL
10 digits after it 14 times. This {14}
quantifier is redundant here, since the length limit is set by the preceding pattern itself.
Also, the anchors are only applied separately to the alternatives, the first will only match at the start of string, and the other will match at the end of string.
You need to use
^(BILL\d{10}|AAAASPA\d{6})$
Or
^(?:BILL\d{10}|AAAASPA\d{6})$
If your regex flavor does not support \d
, use [0-9]
.
See the regex demo.
Details:
^
- start of string(
- start of a grouping construct ((?:...)
is a non-capturing group, not supported by POSIX regex flavor)BILL\d{10}
-BILL
string and then ten digits|
- orAAAASPA\d{6}
-AAAASPA
string and then six digits
)
- end of the grouping$
- end of string.
Note the grouping here that ensures proper anchoring.