前向后瞻正则表达式及其JS例子
2024-08-28 20:20:05
定义
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
见 http://www.cnblogs.com/dolphinx/p/3486214.html 解释的比较好懂。
例子
<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>
最新文章
- NoSQL与RDBMS的九点区别联系
- 2015项目timeline
- iOS -Swift 3.0 -String(字符串常规用法)
- 加快SQL连接速度
- sharepoint 2010 基于AD的Form验证
- Unity 触屏缩放模型
- 在VMware上安装CentOS -7步骤详解
- heritrix1.14.4配置-没有add和change按钮的问题
- vim列编辑
- [UWP]针对UWP程序多语言支持的总结,含RTL
- Dynamics CRM Web API中的and和or组合的正确方式!
- Django---项目
- zabbix添加nginx监控
- maya shell 和 UV shell 的区别
- TCP详解——传输控制协议(总述)
- Ubuntu 8.04嵌入式交叉编译环境arm-linux-gcc搭建过程图解
- VS2012打开项目——已停止工作
- 【原创】when.js2.7.1源码解析
- 执行RF设置顶级测试套件的名称
- jsjl_for_ubuntu12.04