正则表达式 - 修饰符学习笔记
在正则表达式中,修饰符用于改变表达式的匹配行为。下面是一些常用的修饰符及其作用:
i 修饰符
i 修饰符用于忽略大小写匹配。例如,表达式 /hello/i
匹配 "Hello"、"hello" 和 "HELLO"。
javascriptCopy Codeconst regExp = /hello/i;
console.log(regExp.test("Hello")); // true
console.log(regExp.test("hello")); // true
console.log(regExp.test("HELLO")); // true
g 修饰符
g 修饰符用于全局匹配。例如,表达式 /hello/g
匹配所有的 "hello"。
javascriptCopy Codeconst regExp = /hello/g;
console.log("hello world, hello there".match(regExp)); // ['hello', 'hello']
m 修饰符
m 修饰符用于多行匹配。例如,表达式 /^hello/m
匹配每行开头的 "hello"。
javascriptCopy Codeconst regExp = /^hello/m;
console.log("hello world\nhello there".match(regExp)); // ['hello', 'hello']
s 修饰符
s 修饰符用于 dotAll 匹配模式,可以让点号 "." 匹配所有字符,包括换行符。例如,表达式 /.+/s
匹配任意字符串。
javascriptCopy Codeconst regExp = /.+/s;
console.log(regExp.test("hello\nworld")); // true
u 修饰符
u 修饰符用于 Unicode 匹配模式,可以识别 Unicode 字符。例如,表达式 /^\u{20BB7}/u
匹配 Unicode 码点为 0x20BB7
的字符。
javascriptCopy Codeconst regExp = /^\u{20BB7}/u;
console.log(regExp.test("\u{20BB7}123")); // true
y 修饰符
y 修饰符用于粘附匹配模式,确保从上次匹配的位置开始匹配。例如,表达式 /hello/y
将只匹配第一个 "hello"。
javascriptCopy Codeconst regExp = /hello/y;
console.log(regExp.exec("hello world, hello there")); // ['hello']
console.log(regExp.exec("hello world, hello there")); // null
以上就是常用的正则表达式修饰符及其作用。使用这些修饰符可以更加精确地匹配文本。