zoukankan      html  css  js  c++  java
  • RegExp.exec和String.match深入理解

    今天在重新阅读《JavaScript权威指南》的RegExp和String的时候,看到了2个比较容易混淆的函数:RegExp的exec和String的match


    这2个函数都是从指定的字符串中提取符合条件的字串。他们大部分时候的返回结构是一致的,但是在全局检索时,返回的结果差别会很大
    1、正则表达式为非全局检索时,2者是等价的

    返回符合条件的第一个子串以及对应的分组(如果存在存在)构成的伪数组:第一个元素是匹配的字串,余下的为匹配的分组。
    伪数组包含2个属性:
        input     返回要检索的字符串
        index     返回匹配的子串在字符串的位置,在非全局检索时始终为0

    example

     1 var testString = 'Hello World',
     2       reg1 = /w+/;
     3 
     4 var result1 = reg1.exec(testString);
     5 
     6 console.log(result1);//[hello]
     7 console.log(reg1.lastIndex); //0
     8 console.log(result1.index); //0
     9 
    10 var testString = 'Hello World',
    11       reg1 = /(w)+/;
    12 
    13 var result1 = reg1.exec(testString);
    14 
    15 console.log(result1);//[hello, o]
    16 console.log(reg1.lastIndex); //0
    17 console.log(result1.index); //0 

     

    2、正则表达式为全局检索时,2者的处理机制和返回结构不同

    exec处理机制

    当正则表达式为全局检索时,exec会记录每次匹配开始、结束的位置。匹配结束位置存储在正则表达式的lastIndex中,匹配开始位置存储在结果的index中。当exec继续被调用时,正则表达式会从lastIndex进行新的匹配,并返回新的符合条件的子串及分组,并更新正则表达式的lastIndex。重复这样的操作,直到全部匹配完(exec返回null)。此时正则表达式的lastIndex为0。

    match处理机制

    match在要匹配的正则表达式为全局检索时,会直接返回字符串中符合条件的子串数组(不包含分组,即使存在分组)。

    example

     1 var testString = 'Hello World',
     2     reg1 = (w+), result;
     3 
     4 while((result=reg1.exec(testString)) != null){
     5     console.log(result);
     6     console.log(result.index,'-',reg1.lastIndex);
     7 }
     8 //["Hello", "Hello", index: 0, input: "Hello World"]
     9 //0 "-" 5
    10 //["World", "World", index: 6, input: "Hello World"]
    11 //6 "-" 11
    12 
    13 result = testString.match(reg1);
    14 console.log(result);
    15 console.log(result instanceOf Array);
    16 //["Hello", "World"]
    17 
    18 //result instanceof Array
    19 : true
  • 相关阅读:
    NSUserDefaults 简介,使用 NSUserDefaults 存储自定义对象
    OC,查找字符串2在字符串1中出现的次数
    iOS开发知识碎片----01
    iOS中pch文件的应用
    UIKit性能调优实战讲解
    尽量将View设置为Opaque,iOS开发技巧
    Xcode开发技巧之code snippets(代码片段)
    【工具】openwrt安装记录
    【对象模型】C++模版的编译链接过程——编译器真的会检查所有tocken层面的错误么?
    【转】利用TCMalloc优化Nginx的性能
  • 原文地址:https://www.cnblogs.com/guojiao1600/p/5445299.html
Copyright © 2011-2022 走看看