zoukankan      html  css  js  c++  java
  • JavaScript正则表达式方法总结

    str.match(reg)

    1.reg没有全局标志g,match将只执行一次匹配。匹配成功返回一个数组,arr = [$0,$1,$2,...,index,str],匹配失败返回null。

       arr中的参数说明,$0是匹配文本,$i是第i个子表达式匹配的文本,index是$0在stringObject中的起始位置,str是对字符串对象的引用

    2.reg有全局标志g,macth将执行全局检索。匹配成功返回一个数组,arr = [str0,str1,str2,...],匹配失败返回null。

       arr中的参数说明,str0是匹配文本,stri是匹配的子字符串(是对整个reg的匹配,非子表达式),没有额外参数。


    str.search(reg)

    返回第一个与reg匹配的子串的起始位置,没有匹配返回-1.


    reg.exec(str)

    1. reg没有全局标志g,匹配成功返回一个数组,arr = [$0,$1,$2,...,index,str],匹配失败返回null,与string.match相同

    2. reg有全局标志g,exec会在reg的lastIndex属性指定的字符处开始检索字符串,找到匹配文本,lastIndex会设置该匹配文本的最后一个字符的下一个
      位置。找不到匹配文本,返回null,lastIndex重置为0

    如果在一个字符串中完成了一次模式匹配之后要开始检索新的字符串,就必须手动地把 lastIndex 属性重置为 0

    例如:

    var str = "Visit W3School"; 
    var patt = new RegExp("W3School","g");
    var result;
    
    while ((result = patt.exec(str)) != null) {
        document.write(result);
        document.write("<br />");
        document.write(patt.lastIndex);
    }

    或者直接

    while (result = patt.exec(str)) {
        document.write(result);
        document.write("<br />");
        document.write(patt.lastIndex);
    }

    reg.test(str)

    返回字符串中是否含有与reg匹配的文本,有则true,无则false。

  • 相关阅读:
    JAVA List中剔除空元素(null)的方法
    onchange onpropertychange 和 oninput 事件的区别
    window.open()与window.showModuleDialog()
    Eclipse 安装插件(aptana、svn 、git、Java EE、JSHint)
    数字组合 · Combination Sum
    分割回文串 · Palindrome Partitioning
    N皇后问题12 · N-Queens
    全排列12 · Permutations
    Course Schedule课程表12(用Topological Sorting)
    133克隆图 · Clone Graph
  • 原文地址:https://www.cnblogs.com/mengff/p/6140552.html
Copyright © 2011-2022 走看看