zoukankan      html  css  js  c++  java
  • Javascript正则中的exec和match

    分几种情况说明

    1.假设re中不是全局的也就是不带g

    var str = "cat3 hat4";
            var re = /w+d/;
            var ex = re.exec(str);
            var mt = str.match(re);
            console.log(ex);
            console.log(mt);

    结果是["cat3"] 也就是说假设不带g的情况那么..这2个返回的一样 那么就是exec和match 不是全局的时候都是返回匹配到的第一个假设没有返回null

    2.假设re中带g, 也就是全局的

    var str = "cat3 hat4";
            var re = /w+d/g;
            var ex = re.exec(str);
            var mt = str.match(re);
            console.log(ex);
            console.log(mt);

    结果是["cat3"]     ["cat3", "hat4"]  这2个就有差别了.记住exec就算是全局的情况下也是仅仅返回第一个与re匹配的 而match会返回全部匹配到的

    3.假设re中带分组可是不带g

    var str = "cat3 hat4";
            var re = /w+(d)/;
            var ex = re.exec(str);
            var mt = str.match(re);
            console.log(ex);
            console.log(mt);
    都是["cat3", "3"] 也就是说假设带分组可是有不带g 这2个方法结果是一样的..第一个元素是匹配的 第2个開始就是分组1,,,,

    4.假设re中带分组也带g

    var str = "cat3 hat4";
            var re = /w+(d)/g;
            var ex = re.exec(str);
            var mt = str.match(re);
            console.log(ex);
            console.log(mt);

    ["cat3", "3"]  ["cat3", "hat4"]  这次结果不同了..exec是和不带g的一样 可是match 因为是全局的所以返回就是全部匹配的 没有分组


    还有他们2个exec是正则对象的方法    而match是字符串的方法

  • 相关阅读:
    distributed caching for .net applications
    Linux_18/ mysql
    找到一本不错的Linux电子书,附《Linux就该这么学》章节目录。
    LinuxProbe/ 疑问ABC
    Linux_15/ autofs, DNS
    Linux_14/ SAMBA, NFS
    Linux_13/ 虚拟网站主机功能,Vsftpd
    Linux_12/ Apache, SELinux
    Linux_11/ firewalld-config, SSH, bounding
    Linux_10/ iptables & firewalld
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6811659.html
Copyright © 2011-2022 走看看