实现javaScript 正则表达式的反向预查

it2026-02-04  2

目录

BUG解决方法解法一:解法二 参考资料

BUG

工作时时写了一个正则表达式匹配字符串首尾没有被转移的空格,测试时发现在IE浏览器中会报错,在Chrome中正常。正则表达式如下:

const spaceReg = /(^(\s+))|((?<!\\)(\s+)$)/g;

查资料后发现是因为JavaScript语言的正则表达式不能支持所有的正则表达式。 支持的有:

名称字符正向肯定预查( look ahead positive assert )(?=pattern)正向否定预查(look ahead negative assert)(?!pattern)……

不支持的有:

名称字符反向肯定预查( look behind positive assert )(?<=pattern)反向否定预查( look behind negative assert)(?<!pattern)……

ES2018引入了反向肯定预查,V8引擎4.9版(Chrome 62)已经支持。 所以这段正则表达式在IE浏览器中就会报错。

解决方法

stack overflow上有关于js 反向预查 的回答,其中两种解法如下:

解法一:

例:[‘max-height’, ‘line-height’] :match max-height but not line-height, the token being height

reverse the input string var str1 = "max-height".split("").reverse().join(""); var str2 = "line-height".split("").reverse().join(""); match with a reversed regex var reversedReg = /thgieh(?!(-enil))/; reversedReg.test(str1); // true reversedReg.test(str2); // false

解法二

例:Match a double-l but not if it is preceded by “ba”.

var newString = "Fall ball bill balll llama".replace(/(ba)?ll/g, function($0,$1){ return $1?$0:"[match]";}); // Fa[match] ball bi[match] balll [match]ama

参考资料

ECMAScript 6 入门 Javascript: negative lookbehind equivalent

最新回复(0)