How browsers word it
| Chrome and Node (V8) | Invalid regular expression: /(?P<year>\d{4})/: Invalid group |
|---|---|
| Firefox | SyntaxError: invalid regexp group |
| Safari | SyntaxError: Invalid regular expression: invalid group specifier name |
Common causes
A Python named group
Python writes (?P<year>...). JavaScript has no P in a named group.
Input
(?P<year>\d{4})Regex Tester says
Invalid regular expression: /(?P<year>\d{4})/: Invalid groupA group name that starts with a digit
A group name must start with a letter or an underscore.
Input
(?<1a>x)
Regex Tester says
Invalid regular expression: /(?<1a>x)/: Invalid capture group name
The same name used twice
Each named group needs its own name within one pattern.
Input
(?<n>a)(?<n>b)
Regex Tester says
Invalid regular expression: /(?<n>a)(?<n>b)/: Duplicate capture group name
The JavaScript form works
Without the P, the same group is valid.
Input
(?<year>\d{4})Regex Tester says
Compiles and matches
How to fix it
- Write named groups as (?<name>...), and back-references as \k<name>.
- Start every group name with a letter or underscore, and use each name once.
- When you port a pattern from Python, PCRE or Java, check the group syntax first.
- Paste the pattern into the regex tester to see the exact error.