zoukankan      html  css  js  c++  java
  • 正则的捕获

    正则的捕获:exec,返回的结果是数组或null

    先看个demo

    var reg = /d+/
    var str = "hua123hua456";
    var result = reg.exec(str);
    console.dir(result) // ["123", index: 3, input: "hua123hua456"]
    console.log(reg.lastIndex) // 0
    console.log(result.input) // 原字符串str
    console.log(result.index) // 匹配到字符串的初始index,这里是2

    如果你第一次用exec,估计你是猜不到答案的

    捕获的结果是一个数组,因为有符合正则的字符串,但是只有一个,而且还是123,不是1,或者12之类的.

    这里涉及到捕获的两个特点:贪婪性和懒惰性.

    所谓的贪婪性:每次匹配按照匹配最长的结果捕获的,也就是若1符合正则,12也符合正则,那么将捕获12

    所谓的懒惰性:每次执行exec只捕获第一个匹配的内容,在不进行任何处理的情况下,捕获的始终是第一个匹配的内容,且正则的lastIndex还是默认的0.

    显然真要用的话,这样的缺点很麻烦,所以要克服.

    1.克服懒惰性

    之前说了一个修饰符,g,恩,这里可以用来解决懒惰性.

    加了g之后:正则每一次捕获之后lastIndex的值变成最新的值 下一次捕获从最新的位置开始查找,这样就可以把所有需要捕获的内容都获取到

    看个demo

        var reg = /d+/g;
        var str = "h123u456";
        console.log(reg.lastIndex); // 0
        console.log(reg.exec(str)); // ["123", index: 1, input: "h123u456"]
        console.log(reg.lastIndex); // 4
        console.log(reg.exec(str)); // ["456", index: 5, input: "h123u456"]
        console.log(reg.lastIndex); // 8
        console.log(reg.exec(str)); // null
        console.log(reg.lastIndex); // 0
        console.log(reg.exec(str)); // ["123", index: 1, input: "h123u456"]
        console.log(reg.lastIndex); // 4
        console.log(reg.exec(str)); // ["456", index: 5, input: "h123u456"]
        console.log(reg.lastIndex); // 8
        console.log(reg.exec(str)); // null

    每次捕获到字符串之后,lastIndex会从下一个字符串的位置开始,匹配的结果直到null才算结束,后面会一直重复,所以为了得到所有的字符串,可以写个循环

    function findStr (reg,str) {
           var res = reg.exec(str);
           var arr = [];
           while(res){
               arr[arr.length] = res[0];
               res = reg.exec(str);
           }
          return arr;
      }
    findStr (
    /d+/g,"hua123hua456"); //["123","456"]

     不过其实一般是不用findStr这个方法的,因为字符串对象本身有个match的方法

    "123uu556kk90".match(/d+/g); // ["123","556","90"]别忘了加g,不然只匹配一次,懒惰性

    这个方法的缺陷是获得分组的内容,俗称小正则,这个在下一篇文详说

    2.克服贪婪性

    在量词元字符后面加?即可.

    ?在正则中的作用:
    a. 放在普通的元字符后面表示出现0-1次
    b.放在量词元字符后面是取消捕获时候的贪婪性

    举个栗子

    var regg = /d+?/g;
    findStr (regg,str); // ["1","2","3","4","5","6"]

    回忆下量词元字符:*,+,?,{m,n}

    总结下:

      解决懒惰性,g

      解决贪婪性,?

  • 相关阅读:
    第五次实验报告
    第四次实验报告
    [_UICascadingTextStorage attributesAtIndex:effectiveRange:]: Range or index out of bounds
    真机测试时出现 could not find developer disk image问题
    UItableview正在滚动的时候进行操作容易出问题
    NSArray NSMutableArray 初始化
    日志报错Can't add self as subview
    设置statusBar状态栏颜色
    网站视频url地址获取
    ios9 xcode7以后编译需要进行的几项设置
  • 原文地址:https://www.cnblogs.com/2han/p/6371307.html
Copyright © 2011-2022 走看看