当前位置:Gxlcms > JavaScript > JS前向后瞻正则表达式定义与用法示例

JS前向后瞻正则表达式定义与用法示例

时间:2021-07-01 10:21:17 帮助过:3人阅读

本文实例讲述了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'

form https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions

例子:

<html>
<head> 
</head> 
<body>
  <input id="test" type="text" value="" />
  <input id="test" type="text" value="" />
  <input id="test" type="text" value="" />
  <input id="test" type="text" value="" />
  <input id="test" type="text" value="" />
  <script>
  var testStr = "windows 95"
  /* 1 - 不带子表达式匹配 */
  var testReg = /^windows .*$/
  var result = testStr.match(testReg);
  console.log("/^windows .*$/="+result) // /^windows .*$/=windows 95
  /* 2 - 带子表达式匹配 */
  var testReg = /^windows (.*)$/
  var result = testStr.match(testReg);
  console.log("/^windows (.*)$/="+result) // /^windows (.*)$/=windows 95,95
  /* 3 - 带子表达式,不记录其匹配结果 */
  var testReg = /^windows (?:.*)$/
  var result = testStr.match(testReg);
  console.log("/^windows (?:.*)$/="+result) // /^windows (?:.*)$/=windows 95
  /* 4 - 前瞻匹配,匹配位置,正匹配 */
  var testReg = /^windows (?=95)95$/
  var result = testStr.match(testReg);
  console.log("/^windows (?=.*)$/="+result) // /^windows (?=.*)$/=windows 95
  /* 5 - 前瞻匹配,匹配位置,负匹配 */
  var testStr = "windows me"
  var testReg = /^windows (?!95)me$/
  var result = testStr.match(testReg);
  console.log("/^windows (?!\d*)$/="+result) // /^windows (?!d*)$/=windows me
  </script>
</body>
</html>

希望本文所述对大家JavaScript程序设计有所帮助。

更多JS前向后瞻正则表达式定义与用法示例相关文章请关注PHP中文网!

人气教程排行