I am trying Javascript's regular expression.
I understand that ' |
' is used to or-ing two regular expression.
I created a regex /^a*|b*$/
, and I want it to detect any string that contains only charater of 'a' or 'b'.
But when I try /^a*|b*$/.test('c')
, it produces true
?
What I am missing understading of ' |
' operator?
Here's my code:
let reg = /^a*|b*$/;
< undefined
reg.test('c');
< true
|
has very low precedence. ^a*|b*$
matches
^a*
b*$
ie either a string beginning with 0 or more 'a's or a string ending with 0 or more 'b's. (Because matching 0 'a's is allowed by the regex, any string will match (because every string has a beginning).)
To properly anchor the match on both sides, you need
/^(?:a*|b*)$/
(the (?:
)
construct is a non-capturing group).
You could also use
/^a*$|^b*$/
instead.
Note that both of these regexes will only match strings like aa
, bbbbbb
, etc., but not aba
. If you want to allow the use of mixed a/b characters in a string, you need something like
/^(?:a|b)*$/
The OR in your example will split the expression in these alternatives: ^a*
and b*$
.
You can use groups to delimit the alternatives
Something like
/^(a*|b*)$/
This will match empty strings, strings that contains only a
characters and strings that contain only b
characters.
If you're looking to match strings that contain both a
and b
characters, you can use something like:
/^[ab]*$/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.