javascriptregexalternation

How to use 'or' operator in regex properly?


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

Solution

  • | has very low precedence. ^a*|b*$ matches

    i.e. 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)*$/