zoukankan      html  css  js  c++  java
  • 一道关于"/g"笔试题

    正则里“g”表示全局(global)的意思,比如当替换字符串时,如果正则不加g,则只替换一次。

    str = 'hello, jack, hello, lily';
    reg = /hello/;
    res = str.replace(reg, 'hi');
    console.log(res); // 'hi, jack, hello, lily'
    

    第二个hello未被替换,正则reg换成“/hello/g”后则全部替换。

    “g”还有一个作用是它会记录上次匹配时的位置(lastIndex)。这道题如下

    var reg = /abc/g;
    var str = 'abcd';
    reg.test(str);
    reg.test(str);
    

    两次test的结果分别是什么? 相信不少人会迷惑。

    这种情况Perl里也会发生

    use 5.012;
    
    my $str = 'abcd';
    if ($str =~ /abc/g) {
      say 'true';
    } else {
      say 'false';
    }
    if ($str =~ /abc/g) {
      say 'true';
    } else {
      say 'false';
    }
    

    对于不同的正则对象,JS中会从字符串重新开始,因此以下两次输出都是true。

    reg1 = /ab/g;
    reg2 = /cd/g;
    str = 'abcd';
    console.log(reg2.test(str));
    console.log(reg1.test(str));
    

    但Perl中第二次却是false,因为它记住了上次匹配的位置。从字符d后再去匹配ab就匹配不上了。

    use 5.012;
    
    my $str = 'abcd';
    if ($str =~ /cd/g) {
    	say 'true';
    } else {
    	say 'false';
    }
    if ($str =~ /ab/g) {
    	say 'true';
    } else {
    	say 'false';
    }
    

      

  • 相关阅读:
    洛谷 P2896 [USACO08FEB]Eating Together S
    洛谷 P1564 膜拜
    洛谷 P1684 考验
    洛谷 P2031 脑力达人之分割字串
    洛谷 P2725 邮票 Stamps
    洛谷 P2904 [USACO08MAR]跨河River Crossing
    洛谷 P1929 迷之阶梯
    洛谷 P2375 [NOI2014]动物园
    谷歌浏览器禁止表单自动填充
    SQL数据同步之发布订阅
  • 原文地址:https://www.cnblogs.com/snandy/p/2767264.html
Copyright © 2011-2022 走看看