zoukankan      html  css  js  c++  java
  • 前向后瞻正则表达式及其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

    见 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>
  • 相关阅读:
    JSP 中文乱码显示处理解决方案
    jsp的9大对象
    获取各种路径
    输出自绘制图片
    Emmet基本使用方法
    <input type="file" />浏览时只显示指定文件类型
    使用dockerfile文件创建image
    gunicorn 访问日志配置与项目启动
    制作符合自己需求的镜像 docker image
    linux 查看系统信息
  • 原文地址:https://www.cnblogs.com/lightsong/p/4493393.html
Copyright © 2011-2022 走看看