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。

  • 相关阅读:
    [LeetCode]24. Search Insert Position插入位置
    [LeetCode]23. Set Matrix Zeroes矩阵清零
    [LeetCode]22. 3Sum Closest最近三者之和
    [LeetCode]21. 3Sum三者之和
    [LeetCode]20. Unique Paths II唯一路径
    [LeetCode]19. Unique Paths唯一路径
    [LeetCode]18. Contains Duplicate II重复检测
    [LeetCode]17. Majority Element主元素
    第13章建造者模式
    第15章抽象工厂模式
  • 原文地址:https://www.cnblogs.com/mengff/p/6140552.html
Copyright © 2011-2022 走看看