“combine” 2 Regex With A Logic Or?
I have two patterns for javascript: /^[A-z0-9]{10}$/ - string of exactly length of 10 of alphanumeric symbols. and /^\d+$/ - any number of at least length of one. How to make th
Solution 1:
Note that your ^([A-z0-9]{10})|(\d+)$
pattern matches 10 chars from the A-z0-9
ranges at the start of the string (the ^
only modifies the ([A-z0-9]{10})
part (the first alternative branch), or (|
) 1 or more digits at the end of the stirng with (\d+)$
(the $
only modifies the (\d+)
branch pattern.
Also note that the A-z
is a typo, [A-z]
does not only match ASCII letters.
You need to fix it as follows:
var pattern = /^(?:[A-Za-z0-9]{10}|\d+)$/;
or with the i
modifier:
var pattern = /^(?:[a-z0-9]{10}|\d+)$/i;
See the regex demo.
Note that grouping is important here: the (?:...|...)
makes the anchors apply to each of them appropriately.
Details
^
- start of string(?:
- a non-capturing alternation group:[A-Za-z0-9]{10}
- 10 alphanumeric chars|
- or\d+
- 1 or more digits
)
- end of the grouping construct$
- end of string
Post a Comment for "“combine” 2 Regex With A Logic Or?"