@babel/plugin-transform-duplicate-named-capturing-groups-regex

duplicate-named-capturing-groups-regex - 图1info

This plugin is included in @babel/preset-env, in ES2025.

This plugin transforms regular expression literals to support duplicate named capturing groups. It does not patch the new RegExp constructor, since its arguments cannot be pre-transformed statically: to handle runtime behavior of functions/classes, you will need to use a polyfill instead.

Examples

In

JavaScript

  1. var re = /(?<year>\d{4})-(?<month>\d{2})|(?<month>\d{2})-(?<year>\d{4})/;
  2. console.log(re.exec("02-1999").groups.year);

Out

JavaScript

  1. var re = _wrapRegExp(/(\d{4})-(\d{2})|(\d{2})-(\d{4})/, {
  2. year: [1, 4],
  3. month: [2, 3],
  4. });
  5. console.log(re.exec("02-1999").groups.year);

Installation

  • npm
  • Yarn
  • pnpm
  1. npm install --save-dev @babel/plugin-transform-duplicate-named-capturing-groups-regex
  1. yarn add --dev @babel/plugin-transform-duplicate-named-capturing-groups-regex
  1. pnpm add --save-dev @babel/plugin-transform-duplicate-named-capturing-groups-regex

Usage

babel.config.json

  1. {
  2. "plugins": ["@babel/plugin-transform-duplicate-named-capturing-groups-regex"]
  3. }

Via CLI

Shell

  1. babel --plugins @babel/plugin-transform-duplicate-named-capturing-groups-regex script.js

Via Node API

JavaScript

  1. require("@babel/core").transformSync("code", {
  2. plugins: ["@babel/plugin-transform-duplicate-named-capturing-groups-regex"],
  3. });

Options

runtime

boolean, defaults to true

When this option is disabled, Babel doesn’t wrap RegExps with the _wrapRegExp helper. The output only supports internal group references, and not runtime properties:

JavaScript

  1. var stringRe = /(?:(?<quote>")|(?<quote>')).*?\k<quote>/;
  2. stringRe.test("'foo'"); // "true", works
  3. stringRe.exec("'foo'").groups.quote; // undefined

duplicate-named-capturing-groups-regex - 图2tip

You can read more about configuring plugin options here

References