zoukankan      html  css  js  c++  java
  • 【正则表达式】前瞻,后顾,负前瞻,负后顾, 断言

     
    前瞻: exp1(?=exp2) 查找exp2前面的exp1
    后顾: (?<=exp2)exp1 查找exp2后面的exp1
    负前瞻: exp1(?!exp2) 查找后面不是exp2的exp1
    负后顾: (?<!exp2)exp1 查找前面不是exp2的exp1
    注意:前瞻、后顾、负前瞻、负后顾, 这些表达式只是表示一个位置,跟^与$表示开始与结束一样
     
    前瞻示例:
    var path1 = 'path/hello.html';
    var path2 = 'path/nodata.html';
    var path3 = 'path/index.html';
    //如何取到id如/path/:id,并且id需要去掉.html这个后缀
    //使用前瞻的方法,需要找到.html前面的这个单词
    path1.match(/[w]+(?=.html$)/) //结果:["hello", index: 5, input: "path/hello.html", groups: undefined]
    path2.match(/[w]+(?=.html$)/) //结果:["nodata", index: 5, input: "path/nodata.html", groups: undefined]
    path3.match(/[w]+(?=.html$)/) //结果:["index", index: 5, input: "path/index.html", groups: undefined]

    //(?=.html$)这个表达式表示的意思是在.html$前面这个位置(这个表达式不会产生结果,只表示一个位置),具体意思就是:在字符串结尾($)前面的.html的前面的位置的单词
    后顾示例:
    var path1 = 'path/hello.html';
    var path2 = 'path/nodata.html';
    var path3 = 'path/index.html';
    //如何取到id如/path/:id,并且id需要去掉.html这个后缀
    //使用后顾的方法,需要找到path后面的这个单词
    path1.match(/(?<=path/)[w]+/) //结果:["hello", index: 5, input: "path/hello.html", groups: undefined]
    path2.match(/(?<=path/)[w]+/) //结果:["nodata", index: 5, input: "path/nodata.html", groups: undefined]
    path3.match(/(?<=path/)[w]+/) //结果:["index", index: 5, input: "path/index.html", groups: undefined]
    //(?<=path/)这个表达式的意思是找到 path/ 这个字符串后面的位置(不会产生结果,只表示一个位置)

    负前瞻示例:

    var str = 'a,1,b,2,c,3,'
    //把字符串改成 a=1,b=2,c=3,
    str.replace(/,(?![a-z]|$)/g, '='); //"a=1,b=2,c=3,"
    //(?![a-z]|$)这个表达式表示:找到一个位置,这个位置不在任意字母左边([a-z]表示任意字母,前瞻表示表达式左边的位置)且也不能在结尾的左边

    负后顾示例:

    var str = 'a,1,b,2,c,3,'
    //把字符串改成 a=1,b=2,c=3,
    str.replace(/(?<!d),/g, '=');//"a=1,b=2,c=3,"
    //把非数字后面的,替换成=
    //(?<!d)这个表达式表示:找到一个位置,并且这个位置不在数字的后面
  • 相关阅读:
    poj 1904 King's Quest
    【BZOJ】1051: [HAOI2006]受欢迎的牛
    hdu 2767 Proving Equivalences
    hdu 3234 Exclusive-OR
    poj 1988 Cube Stacking
    poj 1733 Parity game
    hdu 3047 Zjnu Stadium 带权并查集
    poj 1182 食物链 种类并查集
    HDU 3749 Financial Crisis
    【BZOJ】1046 : [HAOI2007]上升序列
  • 原文地址:https://www.cnblogs.com/hellolol/p/11193582.html
Copyright © 2011-2022 走看看