正则表达式笔记

基础

字面量形式定义: /正则/
使用 RegExp 构造函数:new Regexp(正则)

RegExp 的两个参数都是字符串。

  • 全局模式 – g
  • 忽略大小写 – i
  • 查找其中的某个 – [],如/[ab]c/,查找ac或bc

RegExp()

方法:

  • exec()

exec()

属性:

  • index:字符串中匹配模式的起始位置
  • input:要查找的字符串
let text = "cat, bat, sat, fat";
let pattern = /.at/g;
let matches = pattern.exec(text);
console.log(matches.index); // 0
console.log(matches[0]); // cat 返回第一个匹配项
console.log(pattern.lastIndex); // 3

如果在后面再调用 exec() 那么输出的数据就会发送改变。因为在这个模式上设置了 g 标记,所以每次调用 exec()都会在字符串中向前搜索下一个匹配项。

matches = pattern.exec(text);
console.log(matches.index); // 5
console.log(matches[0]); // bat 返回第一个匹配项
console.log(pattern.lastIndex); // 8