RegEx mind***** my brain

Hi, I’ve tried to understand this problem:

console.log(/\(\d{3}\)|\d{5}/.test('(99900')) /*returns TRUE and my logic says it should be FALSE*/

my brain is thinking this way: to be true, the str should contain a ‘(’ followed by 3 digits followed by [either a ‘)’ or 5digits more]. Why am i wrong?

The pipe operator (|) means “or”. So you are matching either /\(\d{3}\)/ or /\d{5}/.

I like to use regex playgrounds like this to mess around with different regex.

Yes, regex is very confusing. But it’s also really powerful and cool.

I still don’t get why JS is grouping /\(\d{3}\)/ instead of apply the OR operation to /\)/ OR /\d{3}/

I think it just has to do with precedence and order or operations. Every language has to make choices like that. It seems that when a | is outside a bracket expression, they get evaluated after the regex is. That’s just how it works. Again, I think if mess around with a regex playground for a while, it will make more sense.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.