【正则表达式】前瞻,后顾,负前瞻,负后顾, 断言

 
前瞻: exp1(?=exp2) 查找exp2前面的exp1
后顾: (?<=exp2)exp1 查找exp2后面的exp1
负前瞻: exp1(?!exp2) 查找后面不是exp2的exp1
负后顾: (?<!exp2)exp1 查找前面不是exp2的exp1
注意:前瞻、后顾、负前瞻、负后顾, 这些表达式只是表示一个位置,跟^与$表示开始与结束一样
 
前瞻示例:
var path1 = 'path/hello.html';
var path2 = 'path/nodata.html';
var path3 = 'path/index.html';
//如何取到id如/path/:id,并且id需要去掉.html这个后缀
//使用前瞻的方法,需要找到.html前面的这个单词
path1.match(/[w]+(?=.html$)/) //结果:["hello", index: 5, input: "path/hello.html", groups: undefined]
path2.match(/[w]+(?=.html$)/) //结果:["nodata", index: 5, input: "path/nodata.html", groups: undefined]
path3.match(/[w]+(?=.html$)/) //结果:["index", index: 5, input: "path/index.html", groups: undefined]

//(?=.html$)这个表达式表示的意思是在.html$前面这个位置(这个表达式不会产生结果,只表示一个位置),具体意思就是:在字符串结尾($)前面的.html的前面的位置的单词
后顾示例:
var path1 = 'path/hello.html';
var path2 = 'path/nodata.html';
var path3 = 'path/index.html';
//如何取到id如/path/:id,并且id需要去掉.html这个后缀
//使用后顾的方法,需要找到path后面的这个单词
path1.match(/(?<=path/)[w]+/) //结果:["hello", index: 5, input: "path/hello.html", groups: undefined]
path2.match(/(?<=path/)[w]+/) //结果:["nodata", index: 5, input: "path/nodata.html", groups: undefined]
path3.match(/(?<=path/)[w]+/) //结果:["index", index: 5, input: "path/index.html", groups: undefined]
//(?<=path/)这个表达式的意思是找到 path/ 这个字符串后面的位置(不会产生结果,只表示一个位置)

负前瞻示例:

var str = 'a,1,b,2,c,3,'
//把字符串改成 a=1,b=2,c=3,
str.replace(/,(?![a-z]|$)/g, '='); //"a=1,b=2,c=3,"
//(?![a-z]|$)这个表达式表示:找到一个位置,这个位置不在任意字母左边([a-z]表示任意字母,前瞻表示表达式左边的位置)且也不能在结尾的左边

负后顾示例:

var str = 'a,1,b,2,c,3,'
//把字符串改成 a=1,b=2,c=3,
str.replace(/(?<!d),/g, '=');//"a=1,b=2,c=3,"
//把非数字后面的,替换成=
//(?<!d)这个表达式表示:找到一个位置,并且这个位置不在数字的后面
原文地址:https://www.cnblogs.com/hellolol/p/11193582.html