2. 正则表达式必知必会-匹配单个字符
2.1 匹配纯文本
const str = 'Hello my name is wendy. My website is https://github.com/lwl0812/wendys-site.';
const reg = /wendy/g;
let match;
while ((match = reg.exec(str))) {
console.log(match[0], match.index);
}
// wendy 17
// wendy 65
2.1.1 有多个匹配结果
使用全局匹配 g
2.1.2 字母的大小写问题
使用 i 标志强制执行不区分大小写的搜索。
2.2 匹配任意字符
const str =
'sales1.xls\n' +
'orders3.xls\n' +
'sales2.xls\n' +
'sales3.xls\n' +
'apac1.xls\n' +
'europe2.xls\n' +
'na1.xls\n' +
'na2.xls\n' +
'sa1.xls';
const reg = /sales./g;
let match;
while ((match = reg.exec(str))) {
console.log(match[0]);
}
// sales1
// sales2
// sales3
const str =
'sales1.xls\n' +
'orders3.xls\n' +
'sales2.xls\n' +
'sales3.xls\n' +
'apac1.xls\n' +
'europe2.xls\n' +
'na1.xls\n' +
'na2.xls\n' +
'sa1.xls';
const reg = /.a./g;
let match;
while ((match = reg.exec(str))) {
console.log(match[0]);
}
// sal 匹配三次
// pac
// na1
// na2
// sa1
2.3 匹配特殊字符
const str =
'sales1.xls\n' +
'orders3.xls\n' +
'sales2.xls\n' +
'sales3.xls\n' +
'apac1.xls\n' +
'europe2.xls\n' +
'na1.xls\n' +
'na2.xls\n' +
'sa1.xls';
const reg = /.a.\.xls/g;
let match;
while ((match = reg.exec(str))) {
console.log(match[0]);
}
// na1.xls
// na2.xls
// sa1.xls