Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firefox gives SyntaxError: invalid regexp group

I have few regular expression used for form validation and I noticed that my project is not accessible through firefox as it shows nothing! but give the error in the console, SyntaxError: invalid regexp group

nicRegex is checking for National Identity Card in my country. Format should be 937962723V or 937962723X or any 11 digit number according to the current format.

phoneRegex is to check phone numbers with my country code. 94121212121 or 0762323232

const nicRegex = /^(?:19|20)?\d{2}(?:[01235678]\d\d(?<!(?:000|500|36[7-9]|3[7-9]\d|86[7-9]|8[7-9]\d)))\d{4}(?:[vVxX])$/;

like image 851
Hasini Silva Avatar asked Apr 20 '19 13:04

Hasini Silva


2 Answers

TLDR; Use named capture groups with caution (or just don't use them)

For me, it was because I thought I'd be clever and try to used named capture groups in my regex... Firefox punished me.

Doesn't work: /(?<text>[a-z]+)/

Does work: /([a-z]+)/

like image 195
Nick Grealy Avatar answered Nov 10 '22 06:11

Nick Grealy


The negative lookbehind (not currently supported in Safari) is used here to restrict the previous three digits. This restriction can be performed equally well with a negative lookahead, just it needs to be placed before the 3-digit pattern:

(?:[0-35-8]\d\d(?<!(?:000|500|36[7-9]|3[7-9]\d|86[7-9]|8[7-9]\d)))

should look like

(?!000|500|36[7-9]|3[7-9]\d|86[7-9]|8[7-9]\d)[0-35-8]\d\d

Note the non-capturing groups are redundant here, I removed them, and [01235678] = [0-35-8].

The final regex looks like

/^(?:19|20)?\d{2}(?!000|500|36[7-9]|3[7-9]\d|86[7-9]|8[7-9]\d)[0-35-8]\d\d\d{4}[vVxX]$/

See the regex demo and the Regulex graph:

enter image description here

like image 40
Wiktor Stribiżew Avatar answered Nov 10 '22 07:11

Wiktor Stribiżew