在 JavaScript 中,RegExp
对象的修饰符用于控制正则表达式的匹配行为。以下是常见的修饰符及其含义:
g
(Global,全文匹配)const regex = /hello/g;
const str = "hello world, hello JavaScript!";
console.log(str.match(regex)); // 输出 ["hello", "hello"]
i
(Ignore Case,忽略大小写)const regex = /hello/i;
const str = "Hello World!";
console.log(str.match(regex)); // 输出 ["Hello"]
m
(Multiline,多行匹配)^
和 $
仅匹配字符串的开头和结尾。使用 m
修饰符后,它们还会匹配每一行的开头和结尾。const regex = /^hello/m;
const str = "hello world\nhello JavaScript!";
console.log(str.match(regex)); // 输出 ["hello"]
s
(Dot All,单行模式).
可以匹配包括换行符在内的任何字符。默认情况下,.
不匹配换行符。const regex = /hello.*world/s;
const str = "hello\nworld";
console.log(regex.test(str)); // 输出 true
u
(Unicode,Unicode模式)const regex = /\u{1F600}/u; // 表示查找 Unicode 编码为 1F600 的字符
const str = "";
console.log(regex.test(str)); // 输出 true
y
(Sticky,粘性匹配)g
类似,但 y
修饰符只匹配从当前索引开始的内容,无法从中间跳过字符进行匹配。const regex = /hello/y;
const str = "hello hello";
regex.lastIndex = 6; // 设置搜索位置
console.log(regex.test(str)); // 输出 true
g
:全局匹配。i
:忽略大小写。m
:多行模式。s
:单行模式(使 .
匹配包括换行符在内的所有字符)。u
:Unicode 模式。y
:粘性匹配,从目标字符串的当前位置开始匹配。这些修饰符可以单独使用,也可以组合使用,以实现更复杂的正则表达式匹配行为。