RegExp断言

先行断言

  • lookahead assertionxy之前才匹配,格式为/x(?=y)/
  • negative lookahead assertion:只有x不在y之前才匹配,格式为/x(?!y)/
1
2
3
4
let str = 'now is 02:11:44'

/\d+(?=:)/.exec(str) // ['02']
/\d+(?!\.)/.exec(str) // ['0']

后行断言

  • lookbehind assertionx只有在y后面才匹配,格式为/(?<=y)x/
  • negative lookbehind assertion:只有x不在y后面才匹配,格式为/(?<!y)x/
1
2
3
4
let str = 'now is 02:11:44'

/(?<=:)\d+/.exec(str) // ['11']
/(?<!:)\d+/.exec(str) // ['02']