正则表达式是前端开发中广泛使用的一种工具,它可以帮助我们从字符串中提取出需要的内容。在 ES12 中,正则表达式得到了一些改进,本文将为大家介绍这些新特性及其用法。
RegExp 方法
在 ES12 中,RegExp 增加了两个新方法:matchAll() 和 replaceAll()。
matchAll()
matchAll() 方法返回一个迭代器,该迭代器包含与正则表达式匹配的所有子字符串。它和 match() 方法的不同之处是,match() 方法只会返回第一个匹配到的子字符串。
使用 matchAll() 方法的示例代码如下:
const regex = /t(e)(st(\d?))/g;
const str = 'test1test2test3';
for (const match of str.matchAll(regex)) {
console.log(match);
}输出如下:
["test1", "e", "st1", "1", index: 0, input: "test1test2test3", groups: undefined] ["test2", "e", "st2", "2", index: 4, input: "test1test2test3", groups: undefined] ["test3", "e", "st3", "3", index: 8, input: "test1test2test3", groups: undefined]
replaceAll()
replaceAll() 方法可以使用新字符串替换掉所有匹配到的子字符串。和 replace() 方法的不同之处是,replace() 方法只会替换第一个匹配到的子字符串。
使用 replaceAll() 方法的示例代码如下:
const str = 'test one, test two, test three'; const regex = /test/g; const newStr = str.replaceAll(regex, 'replace'); console.log(newStr); // 'replace one, replace two, replace three'
特定字符集增强
在 ES12 中,正则表达式内的特定字符集也进行了增强。
\p{...} 和 \P{...}
\p{...} 表示匹配一个指定的 Unicode 属性值,\P{...} 则表示匹配除指定 Unicode 属性值以外的内容。
例如,\p{Script=Greek} 表示匹配希腊语字母。
使用 \p{...} 和 \P{...} 的示例代码如下:
const regex = /\p{Script=Greek}/u;
const str = 'Καλημέρα';
console.log(str.match(regex)); //["Κ", "α", "λ", "η", "μ", "έ", "ρ", "α"]纵向匹配增强
在 ES12 中,正则表达式的纵向匹配也得到了增强。
纵向匹配是指同时匹配多个字符的一种方式。例如,[aeiou] 匹配单个元音字母,而 (red|blue) 匹配 red 或 blue。
在 ES12 中,纵向匹配支持使用具名捕获组。具名捕获组使用 (?<name>...) 格式。捕获的内容会被放入一个对象中。
示例代码:
const regex = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/;
const str = '2021-06-28';
console.log(str.match(regex).groups); // {year: "2021", month: "06", day: "28"}后行断言
在 ES12 中,正则表达式增加了后行断言。后行断言用来限制在匹配的内容前必须出现指定的字符串或字符。
后行断言的语法为 (?<=...)。
示例代码:
const regex = /(?<=(blue|red) )shirt/; const str = 'red shirt'; console.log(str.match(regex)); // ['shirt']
结语
本文介绍了 ES12 中正则表达式的一些新特性。这些新特性可以让我们更方便地使用正则表达式,提高开发效率。如果你还没有使用这些新特性,不妨试一试。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d64852a941bf7134bfc2ee