fjordtools / Errors / Regex: Invalid group

SyntaxError: Invalid regular expression: Invalid group

A group that starts with (? uses a form the JavaScript engine does not know. The most common cause is a pattern copied from Python, where a named group is written (?P<name>...). In JavaScript it is (?<name>...). Names must also start with a letter and be unique within the pattern.

Fjordtools team · Seen in Chrome and Node (V8) · Published · 1 min read

How browsers word it

Chrome and Node (V8)Invalid regular expression: /(?P<year>\d{4})/: Invalid group
FirefoxSyntaxError: invalid regexp group
SafariSyntaxError: Invalid regular expression: invalid group specifier name

Common causes

  1. 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 group
  2. A 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
  3. 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
  4. 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

  1. Write named groups as (?<name>...), and back-references as \k<name>.
  2. Start every group name with a letter or underscore, and use each name once.
  3. When you port a pattern from Python, PCRE or Java, check the group syntax first.
  4. Paste the pattern into the regex tester to see the exact error.

Related errors

More error explainers are coming

See all errors.