@babel/plugin-transform-named-capturing-groups-regex
这个插件包含在 @babel/preset-env 中,在 ES2018 中。
注意:这个插件生成的代码需要 ES6 正则表达式功能。如果你需要支持较老的浏览器,请使用 runtime: false 选项或引入合适的 polyfill(例如 core-js)。
这个插件将普通的正则表达式 字面量 转换为支持命名捕获组的形式。它不会修改 new RegExp 构造函数,因为它的参数无法在静态阶段预先转换:要处理函数/类的运行时行为,你需要使用 polyfill。
🌐 This plugin transforms regular expression literals to support 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
在
var re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
console.log(re.exec("1999-02-29").groups.year);
出
var re = _wrapRegExp(/(\d{4})-(\d{2})-(\d{2})/, { year: 1, month: 2, day: 3 });
console.log(re.exec("1999-02-29").groups.year);
安装
🌐 Installation
- npm
- Yarn
- pnpm
- Bun
npm install --save-dev @babel/plugin-transform-named-capturing-groups-regex
yarn add --dev @babel/plugin-transform-named-capturing-groups-regex
pnpm add --save-dev @babel/plugin-transform-named-capturing-groups-regex
bun add --dev @babel/plugin-transform-named-capturing-groups-regex
用法
🌐 Usage
使用配置文件(推荐)
🌐 With a configuration file (Recommended)
{
"plugins": ["@babel/plugin-transform-named-capturing-groups-regex"]
}
通过 CLI
🌐 Via CLI
babel --plugins @babel/plugin-transform-named-capturing-groups-regex script.js
通过 Node API
🌐 Via Node API
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-named-capturing-groups-regex"],
});
选项
🌐 Options
runtime
boolean,默认是 true
当这个选项被禁用时,Babel 不会用 _wrapRegExp 助手封装正则表达式。输出只支持内部组引用,不支持运行时属性:
🌐 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:
var stringRe = /(?<quote>"|').*?\k<quote>/;
stringRe.test("'foo'"); // "true", works
stringRe.exec("'foo'").groups.quote; // Error
你可以在这里了解更多关于配置插件选项的内容