正则表达式里提供了多个标志位符号,来匹配复杂的字符文本场景。今天来简单学习一下
g (global)
- 全局匹配
- 当使用g标志时,正则表达式会在整个字符串中查找所有匹配的子串,而不仅仅是第一个匹配项。
const str = 'abc abc abc';
const regex = /abc/g;
const matches = str.match(regex);
console.log(matches); // 输出: ["abc", "abc", "abc"]
i(ignore)
- 忽略大小写。
- 当使用i标志时,正则表达式会忽略字符的大小写进行匹配。
const str = 'Hello World';
const regex = /hello/i;
const match = str.match(regex);
console.log(match[0]); // 输出: ["Hello"]
m(multiline)
- 多行匹配。
- 当使用m标志时,^和$会匹配字符串中的每一行的开始和结束位置,而不仅仅是整个字符串的开始和结束位置。
- 适用于模板字符串``或者读取文件内容
const str =`
Line 1
Line 2
Line 3
`;
const regex = /Line \d/m;
const matches = str.match(regex);
console.log(matches[0]); // 输出: ["Line 1"]
s(dot all)
- 点号匹配所有字符。
- 当使用s标志时,点号(.)会匹配包括换行符在内的所有字符。
//使用s标志时,点号(.)会匹配包括换行符在内的所有字符。
const str = 'Hello\nWorld';
const regex = /Hello.World/s;
const match = str.match(regex);
console.log(match[0]); // 输出: ["Hello\nWorld"]
u(unicode)
- Unicode模式。
- 当使用u标志时,正则表达式会将字符串视为Unicode字符序列进行匹配。
const str = '';
const regex = /\u{1F600}-\u{1F603}/u;
const match = str.match(regex);
console.log(match[0]); // 输出: [""]
y(sticky)
- 粘性匹配。
- 当使用y标志时,正则表达式会从lastIndex属性指定的位置开始匹配,并且只匹配从该位置开始的字符串。
- 可以通过设置lastIndex索引位置,来决定匹配的开始位置
const str = 'abcabc';
const regex = /abc/y;
regex.lastIndex = 1;
const match = str.match(regex);
console.log(match); // 输出: null