断言表达式
‘?=’正向向前查找
‘?!’负向向前查找
‘?<=’正向向后查找
‘?<!’负向向后查找
先举个列子
var str = '我爱你 我爱 想爱 爱 爱你'
var res = str.match(/爱(?=你)/g)// ["爱", "爱"]
var res = str.match(/爱(?!你)/g)//["爱", "爱", "爱"]
var res = str.match(/(?<=我)爱/g)//["爱", "爱"]
var res = str.match(/(?<!我)爱/g)//["爱", "爱", "爱"]
下面用大白话阐述说明
str.match(/爱(?=你)/g):爱字后面要有你
str.match(/爱(?!你)/g):爱字后面不要你
str.match(/(?<=我)爱/g):爱字前面要有我
str.match(/(?<!我)爱/g):爱字前面不要我
let uu = 'http://www.baidu.com'
let res = uu.match(/.+(?=:)/)
console.log(res)
//----------控制台输出----------------
0: "http"
groups: undefined
index: 0
input: "http://www.baidu.com"
length: 1
这种查找方式只是找到即可,返回的结果中不会体现找到了“:”本身,即没有消费,而(:)匹配则会返回“:”本身,即消费了,但每次都消费,即浪费时间和资源,也存在不必要的隐患
let str = 'I buy paid $30 for 100 apples'
let res = str.match(/(?!\$)\d+/)
console.log(res)
使用负向向前查找得到结果
//------------控制台输出-------------------
0: "30"
groups: undefined
index: 12
input: "I buy paid $30 for 100 apples"