RegExp修饰符有哪些?

66 阅读1分钟

"```markdown

RegExp修饰符

在JavaScript中,正则表达式(RegExp)可以通过修饰符来增强匹配功能。以下是常用的RegExp修饰符及其含义:

1. g - 全局匹配

g修饰符表示全局搜索,即查找字符串中所有匹配项,而不是仅仅找到第一个匹配项。

const str = \"hello world, hello universe\";
const regex = /hello/g;
const matches = str.match(regex); // [\"hello\", \"hello\"]

2. i - 不区分大小写

i修饰符使得匹配不区分大小写。

const str = \"Hello World\";
const regex = /hello/i;
console.log(regex.test(str)); // true

3. m - 多行匹配

m修饰符使得^$可以匹配每一行的开始和结束,而不仅仅是整个字符串的开始和结束。

const str = \"first line\
second line\";
const regex = /^second/m;
console.log(regex.test(str)); // true

4. s - 单行匹配

s修饰符允许.匹配换行符。默认情况下,.不会匹配换行符。

const str = \"hello\
world\";
const regex = /hello.world/s;
console.log(regex.test(str)); // true

5. u - Unicode匹配

u修饰符启用Unicode匹配,使得正则表达式能够处理Unicode字符。

const str = \"𠜎\"; // 一个Unicode字符
const regex = /𠜎/u;
console.log(regex.test(str)); // true

6. y - 粘连匹配

y修饰符表示粘连匹配,要求匹配从目标字符串的当前位置开始,而不是任意位置。

const str = \"hello world\";
const regex = /world/y;
regex.lastIndex = 6;
console.log(regex.test(str)); // true

7. 组合修饰符

可以组合多个修饰符,例如gi表示全局和不区分大小写的匹配。

const str = \"Hello World\";
const regex = /hello/gim;
console.log(str.match(regex)); // [\"Hello\"]

总结

RegExp修饰符为正则表达式提供了灵活性和功能,使得字符串匹配更加强大和精准。理解和合理使用这些修饰符是高效处理文本的关键。