02. 匹配单个字符(学习笔记)

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
' +
  'orders3.xls
' +
  'sales2.xls
' +
  'sales3.xls
' +
  'apac1.xls
' +
  'europe2.xls
' +
  'na1.xls
' +
  'na2.xls
' +
  'sa1.xls';
const reg = /sales./g;
let match;
while ((match = reg.exec(str))) {
  console.log(match[0]);
}
// sales1
// sales2
// sales3

  

const str =
  'sales1.xls
' +
  'orders3.xls
' +
  'sales2.xls
' +
  'sales3.xls
' +
  'apac1.xls
' +
  'europe2.xls
' +
  'na1.xls
' +
  'na2.xls
' +
  '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
' +
  'orders3.xls
' +
  'sales2.xls
' +
  'sales3.xls
' +
  'apac1.xls
' +
  'europe2.xls
' +
  'na1.xls
' +
  'na2.xls
' +
  'sa1.xls';
const reg = /.a..xls/g;
let match;
while ((match = reg.exec(str))) {
  console.log(match[0]);
}
// na1.xls
// na2.xls
// sa1.xls

  

原文地址:https://www.cnblogs.com/lwl0812/p/11216901.html