← 中文资源

简体中文版本

RegExp v 标志启用 Unicode 集合运算

用 RegExp 的 v 标志对 Unicode 字符集做差集与交集,组合文字属性,并用集合记法校验标识符。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

non-greek letters: [ 'Привет' ]
scripts: [ 'Ωμέγα', 'Привет' ]
ascii punctuation: [ '!?' ]
abc_123 true
abc-123 false

实现说明

重复被限制在 for (const value of ["abc_123", "abc-123"]) 里——其余代码按顺序各跑一遍。 演示用的数据放在这几个模块级绑定中:nonGreekLetters、greekOrCyrillic、asciiPunctuation、sample。

使用要点

  • 直接运行文件,输出会带上标签,比如 non-greek letters:、scripts:、ascii punctuation:——输出的每一行都能指回产生它的那次调用。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件用顶层绑定保存自己的状态:nonGreekLetters、greekOrCyrillic、asciiPunctuation。

核心语句

const greekOrCyrillic = /[\p{Script=Greek}\p{Script=Cyrillic}]+/gv;
const nonGreekLetters = /[\p{Letter}--\p{Script=Greek}]+/gv;
const asciiPunctuation = /[\p{Punctuation}&&\p{ASCII}]+/gv;

代码示例

// RegExp with the v flag supports subtraction and intersection in classes.
const nonGreekLetters = /[\p{Letter}--\p{Script=Greek}]+/gv;
const greekOrCyrillic = /[\p{Script=Greek}\p{Script=Cyrillic}]+/gv;
const asciiPunctuation = /[\p{Punctuation}&&\p{ASCII}]+/gv;

const sample = "Ωμέγα 42 Привет!?";

console.log("non-greek letters:", sample.match(nonGreekLetters));
console.log("scripts:", sample.match(greekOrCyrillic));
console.log("ascii punctuation:", sample.match(asciiPunctuation));

const identifier = /^[\p{Letter}\p{Number}_]+$/v;
for (const value of ["abc_123", "abc-123"]) {
  console.log(value, identifier.test(value));
}