免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3198 | 回复: 3
打印 上一主题 下一主题

关于perl正则表达式全局匹配的一个奇怪问题 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2016-06-08 15:01 |只看该作者 |倒序浏览
代码实例如下,当使用全局匹配/g选项时,发现第二个if匹配块不起作用,取消/g选项后恢复正常,请高手帮忙讲解一下原因,多谢!我用的是perl 5.22.1版本。
带/g:
  1. use strict;
  2. use warnings;

  3. my $str = "ab";

  4. if($str =~ m/b/g)
  5. {
  6.     print("find b\n");
  7. }

  8. if($str =~ m/a/g)
  9. {
  10.     print("find a\n");
  11. }
复制代码
程序输出:"find b"

取消/g:
  1. use strict;
  2. use warnings;

  3. my $str = "ab";

  4. if($str =~ m/b/)
  5. {
  6.     print("find b\n");
  7. }

  8. if($str =~ m/a/)
  9. {
  10.     print("find a\n");
  11. }
复制代码
程序输出:"find b  find a"

论坛徽章:
145
技术图书徽章
日期:2013-10-01 15:32:13戌狗
日期:2013-10-25 13:31:35金牛座
日期:2013-11-04 16:22:07子鼠
日期:2013-11-18 18:48:57白羊座
日期:2013-11-29 10:09:11狮子座
日期:2013-12-12 09:57:42白羊座
日期:2013-12-24 16:24:46辰龙
日期:2014-01-08 15:26:12技术图书徽章
日期:2014-01-17 13:24:40巳蛇
日期:2014-02-18 14:32:59未羊
日期:2014-02-20 14:12:13白羊座
日期:2014-02-26 12:06:59
2 [报告]
发表于 2016-06-08 22:12 |只看该作者
回复 1# gaojianchun1984


if($str =~ m/b/g){ ... }    # note: ab
  found the "b" and keep the position 2 (after b)

if($str =~ m/a/g){ ... }    # note: ab
  cannot find the "a" after "b" (postion 2)



$ perldoc perlretut
NAME
    perlretut - Perl regular expressions tutorial

   ...

   Global matching
    The final two modifiers we will discuss here, "//g" and "//c", concern
    multiple matches. The modifier "//g" stands for global matching and allows
    the matching operator to match within a string as many times as possible.
    In scalar context, successive invocations against a string will have "//g"
    jump from match to match, keeping track of position in the string as it
    goes along. You can get or set the position with the "pos()" function.


   

论坛徽章:
0
3 [报告]
发表于 2016-06-08 23:15 来自手机 |只看该作者
多谢大神指点!

论坛徽章:
307
程序设计版块每周发帖之星
日期:2016-04-08 00:41:33操作系统版块每日发帖之星
日期:2015-09-02 06:20:00每日论坛发贴之星
日期:2015-09-02 06:20:00程序设计版块每日发帖之星
日期:2015-09-04 06:20:00每日论坛发贴之星
日期:2015-09-04 06:20:00每周论坛发贴之星
日期:2015-09-06 22:22:00程序设计版块每日发帖之星
日期:2015-09-09 06:20:00程序设计版块每日发帖之星
日期:2015-09-19 06:20:00程序设计版块每日发帖之星
日期:2015-09-20 06:20:00每日论坛发贴之星
日期:2015-09-20 06:20:00程序设计版块每日发帖之星
日期:2015-09-22 06:20:00程序设计版块每日发帖之星
日期:2015-09-24 06:20:00
4 [报告]
发表于 2016-06-08 23:41 |只看该作者
这个问题我也是稀里糊涂的, 今天总是明白了. 谢谢大神指点.
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP