Skip to main content

@babel/plugin-transform-unicode-sets-regex

info

这个插件包含在 @babel/preset-env 中,在 ES2024

这个插件将使用 [RegExp 集合表示法 + 字符串属性](https://github.com/tc39/proposal-regexp-set-notation) 提案中引入的 v 标志的正则表达式,转换为使用 u 标志的正则表达式。

🌐 This plugin transforms regular expressions using the v flag, introduced by the RegExp set notation + properties of strings proposal, to regular expressions that use the u flag.

它只会转换 /.../v 语法,并不会修补 new RegExp 构造函数,因为它的参数无法被静态预转换:要处理函数/类的运行时行为,你需要使用 polyfill。

🌐 It only transforms /.../v syntax and 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.

示例​

🌐 Example

交集​

🌐 Intersection

input.js
/[\p{ASCII}&&\p{Decimal_Number}]/v;

将转变为

🌐 will be transformed to

output.js
/[0-9]/u;

不同之处​

🌐 Difference

input.js
// Non-ASCII white spaces
/[\p{White_Space}--\p{ASCII}]/v;

将转变为

🌐 will be transformed to

output.js
/[\x85\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/u;

字符串的属性​

🌐 Property of Strings

input.js
/^\p{Emoji_Keycap_Sequence}$/v.test("*\uFE0F\u20E3");
// true

将转变为

🌐 will be transformed to

output.js
/^(?:\*️⃣|#️⃣|0️⃣|1️⃣|2️⃣|3️⃣|4️⃣|5️⃣|6️⃣|7️⃣|8️⃣|9️⃣)$/u.test("*\uFE0F\u20E3");
// true

这里有一个支持的属性列表。注意,使用带有 u 标志的字符串属性会报错。

🌐 Here is a list of supported properties. Note that using property of strings with u-flag will error.

input.js
/\p{Emoji_Keycap_Sequence}/u;
// Error: Properties of strings are only supported when using the unicodeSets (v) flag.

安装​

🌐 Installation

npm install --save-dev @babel/plugin-transform-unicode-sets-regex

用法​

🌐 Usage

🌐 With a configuration file (Recommended)

babel.config.json
{
"plugins": ["@babel/plugin-transform-unicode-sets-regex"]
}

通过 CLI​

🌐 Via CLI

Shell
babel --plugins @babel/plugin-transform-unicode-sets-regex script.js

通过 Node API​

🌐 Via Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-unicode-sets-regex"],
});