zoukankan      html  css  js  c++  java
  • 正则的lastIndex 属性

    简介:正则的lastIndex 属性用于规定下次匹配的起始位置。

    注意: 该属性只有设置标志 g 才能使用。

    上次匹配的结果是由方法 RegExp.exec() 和 RegExp.test() 找到的,它们都以 lastIndex 属性所指的位置作为下次检索的起始点。这样,就可以通过反复调用这两个方法来遍历一个字符串中的所有匹配文本。

    注意:该属性是可读可写的。只要目标字符串的下一次搜索开始,就可以对它进行设置。当方法 exec() 或 test() 再也找不到可以匹配的文本时,它们会自动把 lastIndex 属性重置为 0。

      例子一:在字符串中全局试试子字符串 "ain" , 并输出匹配完成之后的 lastIndex 属性:

    var str="The rain in Spain stays mainly in the plain";
    var patt1=/ain/g;
    
    while (patt1.test(str)==true) 
    {
        document.write("'ain' found. Index now at: "+patt1.lastIndex);
        document.write("<br>");
    };


      例子二:多次检索,打印出lastIndex的位置,当检索到最后没有检索出符合的就从头开始检索

    var str="The rain in Spain stays";
    var patt=/ain/g;
    console.log(patt.test(str))//true
    console.log(patt.lastIndex)//8
    console.log(patt.test(str))//true
    console.log(patt.lastIndex)//17
    console.log(patt.test(str))//false
    console.log(patt.lastIndex)//0
    console.log(patt.test(str))//true
    console.log(patt.lastIndex)//8

      例子三:如何避免因由于lastIndex引起bug:每次都创建一个新的RegExp就 可以避免这个问题

    var str="The rain in Spain stays";
    console.log(/ain/g.test(str))//true
    console.log(/ain/g.lastIndex)//0
    console.log(/ain/g.test(str))//true
    console.log(/ain/g.lastIndex)//0
    console.log(/ain/g.test(str))//false
    console.log(/ain/g.lastIndex)//0
    console.log(/ain/g.test(str))//true
    console.log(/ain/g.lastIndex)//0

      

  • 相关阅读:
    oracle10 http://localhost:5500/em打不开引发的问题
    [bbk5383] 第90集 第11章 数据库诊断 06
    [bbk5373] 第88集 第11章 数据库诊断 04
    ORA01157报错"cannot identify/lock data file"
    [bbk5361] 第86集 第11章 数据库诊断 02
    MFC里AfxGetThread()与AfxGetAPP()的区别
    VC++ 6.0 中类不见了
    MFC中的注释宏
    MFC中OnNcLButtonDown和OnNcLButtonUp的添加方法
    MFC用CWindowDC dc(GetParent())不能在标题栏画线的问题
  • 原文地址:https://www.cnblogs.com/aidixie/p/11271186.html
Copyright © 2011-2022 走看看