JS前向后瞻正则表达式定义与用法示例
本文实例讲述了JS前向后瞻正则表达式定义与用法。分享给大家供大家参考,具体如下:
定义
x(?=y)匹配'x'仅仅当'x'后面跟着'y'.这种叫做正向肯定查找。
比如,/Jack(?=Sprat)/会匹配到'Jack'仅仅当它后面跟着'Sprat'。/Jack(?=Sprat|Frost)/匹配‘Jack'仅仅当它后面跟着'Sprat'或者是‘Frost'。但是‘Sprat'和‘Frost'都不是匹配结果的一部分。
x(?!y)匹配'x'仅仅当'x'后面不跟着'y',这个叫做正向否定查找。
比如,/\d+(?!\.)/匹配一个数字仅仅当这个数字后面没有跟小数点的时候。正则表达式/\d+(?!\.)/.exec("3.141")匹配‘141'但是不是‘3.141'
formhttps://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions
前面这篇https://www.nhooo.com/article/84839.htm解释的比较好懂。
例子:
<html>
<head>
</head>
<body>
<inputid="test"type="text"value=""/>
<inputid="test"type="text"value=""/>
<inputid="test"type="text"value=""/>
<inputid="test"type="text"value=""/>
<inputid="test"type="text"value=""/>
<script>
vartestStr="windows95"
/*1-不带子表达式匹配*/
vartestReg=/^windows.*$/
varresult=testStr.match(testReg);
console.log("/^windows.*$/="+result)///^windows.*$/=windows95
/*2-带子表达式匹配*/
vartestReg=/^windows(.*)$/
varresult=testStr.match(testReg);
console.log("/^windows(.*)$/="+result)///^windows(.*)$/=windows95,95
/*3-带子表达式,不记录其匹配结果*/
vartestReg=/^windows(?:.*)$/
varresult=testStr.match(testReg);
console.log("/^windows(?:.*)$/="+result)///^windows(?:.*)$/=windows95
/*4-前瞻匹配,匹配位置,正匹配*/
vartestReg=/^windows(?=95)95$/
varresult=testStr.match(testReg);
console.log("/^windows(?=.*)$/="+result)///^windows(?=.*)$/=windows95
/*5-前瞻匹配,匹配位置,负匹配*/
vartestStr="windowsme"
vartestReg=/^windows(?!95)me$/
varresult=testStr.match(testReg);
console.log("/^windows(?!\d*)$/="+result)///^windows(?!d*)$/=windowsme
</script>
</body>
</html>
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript替换操作技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》、《JavaScript中json操作技巧总结》、《JavaScript错误与调试技巧总结》及《JavaScript数学运算用法总结》
希望本文所述对大家JavaScript程序设计有所帮助。