i have this regex the _ is the whitespace
^([a-z]{4}+)?_([A-Z]{4}+)?_(\d{4}+)?$
which allows alpha_BETA_1920
, I expect it to allow the following values too
alpha
BETA
1920
alpha_BETA
alpha_1920
BETA_1920
The problem is that the _
is static, So all the values above are false
, And my RegEx treats the next false
values as true
alpha__
_BETA_
__1920
alpha_BETA_
alpha__1920
_BETA_1920
P.S. My actual RegEx
contains more than 6 words
instead of the 3 words
as here.
The _
isn't an actualy underscore, Replace it with , I used it because the `` didn't allow me to use it at the beginning or the end of the text.
Try enclosing the whole "letter plus underscore" sub pattern into a group and apply the ?
quantifier. Also, the number shouldn't be optional, should it?
^([a-z]+_)?([A-Z]+_)?(\d+)$
Pattern: /\b[a-z]+(?:_[A-Z]+)?(?:_\d+)?\b|\b(?:[a-z]+_)?(?:[A-Z]+_)?\d+\b|\b[A-Z]+\b/
It matches from the front, or matches from the back of the string, or it matches the middle. See demo for visual.
Or instead of wordboundaries, you can use anchors for improved speed:
Pattern:
/^[a-z]+(?:_[A-Z]+)?(?:_\d+)?$|^(?:[a-z]+_)?(?:[A-Z]+_)?\d+$|^[A-Z]+$/
Or just 2 anchors around a non-capturing group:
/^(?:[a-z]+(?:_[A-Z]+)?(?:_\d+)?|(?:[a-z]+_)?(?:[A-Z]+_)?\d+|[A-Z]+)$/