zoukankan      html  css  js  c++  java
  • 正则中str.match(pattern)与pattern.exec(str)的区别

      这两个函数除了调用对象以及参数不同之外,《javascript高级程序设计》中对exec描述比较详细,对match只是说返回数组跟exec一样。书中并没有说只说了正则在非全局模式下的情况,但是其实在正则全局模式下则有很大区别。

    一、非全局模式下

      在非全局模式下,两种方法返回结果相同,我们以match为例。

      我们首先来看代码

        var str="cat,bat,sat";
        var pattern=/.at/;
        var matches=str.match(pattern);
        console.dir(matches);

      返回结果

    二、全局模式

    1.match

      代码如下

        var str="cat,bat,sat";
        var pattern=/.at/g;
        var matches=str.match(pattern);
        console.dir(matches);

      结果如下

      可以注意到,返回结果把整个字符串中符合正则的结果都列出来放在了结果数据里,而结果数组中也没有了index属性。

    2.exec

      代码如下

    var str="cat,bat,sat";
    var pattern=/.at/;
    var matches=pattern.exec(str);
    console.dir(matches);

      结果如下

      正如书上所说,exec一次只会匹配符合条件的一项,每次调用则会在字符串中继续寻找。

    三、总结

      在全局模式下,match会一下返回所有匹配项;而exec每次只返回一项,下次调用接着向后匹配。

  • 相关阅读:
    Makefile 之 $(Q)
    LeetCode-50-Pow(x, n)
    LeetCode-49. Group Anagrams
    全排列问题全面解析
    LeetCode-47. Permutations II
    LeetCode-46. Permutations
    LeetCode-43. Multiply Strings
    LeetCode-40. Combination Sum II
    LeetCode-39. Combination Sum
    LeetCode-36. Valid Sudoku
  • 原文地址:https://www.cnblogs.com/shytong/p/5306644.html
Copyright © 2011-2022 走看看