Documentación offline JavaScript main

SyntaxError: invalid capture group name in regular expression

main Documentación oficial Licencia CC-BY-SA-2.5Descargado el 2026-08-02

En esta página

The JavaScript exception "invalid capture group name in regular expression" occurs when a named capturing group or named backreference contains an invalid identifier.

Message#

SyntaxError: Invalid regular expression: /(?<1>)/: Invalid capture group name (V8-based)
SyntaxError: invalid capture group name in regular expression (Firefox)
SyntaxError: Invalid regular expression: invalid group specifier name (Safari)

Error type#

{{jsxref("SyntaxError")}}

What went wrong?#

Each named capturing group must have a name that is a valid identifier. You cannot use arbitrary strings as the group identifier.

Examples#

Invalid cases#

```js example-bad /(?<1>\d+) (?<2>\d+)/;

Or you might be building the regex dynamically:

```js example-bad
const tokenTypes = {
  "number literal": /\d+/,
  "string literal": /".+?"/,
  identifier: /[a-zA-Z_]\w*/,
};

const tokenPattern = new RegExp(
  Object.entries(tokenTypes)
    .map(([name, pattern]) => `(?<${name}>${pattern.source})`)
    .join("|"),
);

Valid cases#

```js example-good /(?\d+) (?\d+)/;

If the regex is built dynamically, make sure the names are all valid identifiers. For example:

```js example-good
const tokenTypes = {
  numberLiteral: /\d+/,
  stringLiteral: /".+?"/,
  identifier: /[a-zA-Z_]\w*/,
};

const tokenPattern = new RegExp(
  Object.entries(tokenTypes)
    .map(([name, pattern]) => `(?<${name}>${pattern.source})`)
    .join("|"),
);

See also#