正则表达式

正则表达式

\0,\1,\2 回溯引用

\0 表示整个表达式 \1 代表括号里的子表达式

1
2
3
const str = 'catcat';
str.match(/(cat)\1/);
// ["catcat", "cat", index: 0, input: "catcat", groups: undefined]

(?: ) 非捕获

1
2
3
const s = 'happy';
s.match(/h(?:a)p(py)/)
// ["happy", "py", index: 0, input: "happy", groups: undefined]

(?= ) 前向查找

1
2
3
4
5
const s = 'happy';
s.match(/p(?=p)/)
// ["p", index: 2, input: "happy", groups: undefined]
s.match(/p(?=y)/)
// ["p", index: 3, input: "happy", groups: undefined]

(?! ) 前向负查找

1
2
3
4
5
const s = 'happy';
s.match(/p(?!p)/)
// ["p", index: 3, input: "happy", groups: undefined]
s.match(/p(?!y)/)
// ["p", index: 2, input: "happy", groups: undefined]

(?<= ) 后向查找

1
2
3
4
5
const s = 'happy';
s.match(/(?<=p)p/)
// ["p", index: 3, input: "happy", groups: undefined]
s.match(/(?<=a)p/)
// ["p", index: 2, input: "happy", groups: undefined]

(?<! ) 后向负查找

1
2
3
4
5
const s = 'happy';
s.match(/(?<!a)p/)
// ["p", index: 3, input: "happy", groups: undefined]
s.match(/(?<!p)p/)
// ["p", index: 2, input: "happy", groups: undefined]