正则表达式前瞻后顾,负前瞻,负后顾(?=,?:和?!)理解和应用

前瞻:

haorooms(?=hrms)查找hrms前面的haorooms,表示我们需要匹配hrms的前面

后顾:

(?<=hrms)haorooms查找hrms后面的haorooms

负前瞻:

haorooms(?!hrms)查找后面不是hrms的haorooms,

负后顾:

(?<!=hrms)haorooms查找前面不是hrms的haorooms

例子

console.log("我是中国人".replace(/我是(?=中国)/,"haorooms"))// 输出: 'haorooms中国人',匹配的是中国前面的'我是'

console.log("我是中国人".replace(/(?!中国)/,"haorooms"))// 输出:'haorooms我是中国人'

console.log("我是中国人".replace(/(?:中国)/,"haorooms"))// 输出:'我是haorooms人',匹配'中国'本身

console.log("我是中国人".replace(/(?<=中国)人/,"haorooms"))// 输出:'我是中国haorooms',匹配的是中国后面的'人'

console.log("我是中国人".replace(/(?<!中国)/,"haorooms"))// 输出:'haorooms我是中国人'

例子二

匹配下面的href地址

< br/>您好,欢迎来到haorooms博客 < br/><atarget=_blankhref="www.haorooms.com">前端博客</a>前端 < br/><atarget=_blankhref="resource.haorooms.com">前端资源库</ a>haorooms < br/>

方法1: 匹配,捕获(存储)

正则表达式:

(?<=(href=")).{1,200}(?=(">))

解释:(?<=(href=")) 表示 匹配以(href=")开头的字符串,并且捕获(存储)到分组中 (?=(">)) 表示 匹配以(">)结尾的字符串,并且捕获(存储)到分组中

方法2: 匹配,不捕获(不存储)

正则表达式:

(?<=(?:href=")).{1,200}(?=(?:">))

解释:(?<=(?:href=")) 表示 匹配以(href=")开头的字符串,并且不捕获(不存储)到分组中 (?=(?:">)) 表示 匹配以(">)结尾的字符串,并且不捕获(不存储)到分组中

应用

数字格式化

console.log("1234567890".replace(/\B(?=(?:\d{3})+(?!\d))/g,","))// 输出:'1,234,567,890'