免费注册 查看新帖 |

Chinaunix

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

模式分组/y(.)(.)\2\1/里的向后引用,"\+数字"部分必须有吗? [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-30 11:50 |只看该作者 |倒序浏览
小骆驼第五版讲模式分组的时候,关于向后引用(back reference)部分有这样一个例子:

$_ = "yabba dabba doo";
if (/y(.)(.)\2\1/) { # matches 'abba'
    print "It matched the same after y and d!\n";
}

我对这一节里的向后引用理解得不好。可以理解单独的/y(.)\1/就是要匹配两个重复的字符,也可以理解/(.)(.)\1/可以匹配形如aba这样的轴对称字符。但是对于这个模式里,为什么往(.)\1中间插入(.)\2后就有了匹配形如abba的回文字符的功能呢?

[ 本帖最后由 bequan 于 2009-8-30 21:09 编辑 ]

论坛徽章:
0
2 [报告]
发表于 2009-08-30 12:24 |只看该作者
这又什么问题吗,就是这样啊.

论坛徽章:
0
3 [报告]
发表于 2009-08-30 21:03 |只看该作者
()后面跟一个“\+数字”,我不太明白“\+数字”的作用

论坛徽章:
0
4 [报告]
发表于 2009-08-30 21:48 |只看该作者

回复 #3 bequan 的帖子

Backreferences

Closely associated with the matching variables $1 , $2 , ... are the backreferences \1 , \2 ,... Backreferences are simply matching variables that can be used inside a regexp. This is a really nice feature -- what matches later in a regexp is made to depend on what matched earlier in the regexp. Suppose we wanted to look for doubled words in a text, like 'the the'. The following regexp finds all 3-letter doubles with a space in between:

   1. /\b(\w\w\w)\s\1\b/;

The grouping assigns a value to \1, so that the same 3 letter sequence is used for both parts.

A similar task is to find words consisting of two identical parts:

   1. % simple_grep '^(\w\w\w\w|\w\w\w|\w\w|\w)\1$' /usr/dict/words
   2. beriberi
   3. booboo
   4. coco
   5. mama
   6. murmur
   7. papa

The regexp has a single grouping which considers 4-letter combinations, then 3-letter combinations, etc., and uses \1 to look for a repeat. Although $1 and \1 represent the same thing, care should be taken to use matched variables $1 , $2 ,... only outside a regexp and backreferences \1 , \2 ,... only inside a regexp; not doing so may lead to surprising and unsatisfactory results.

论坛徽章:
0
5 [报告]
发表于 2009-08-30 22:47 |只看该作者
明白了,back reference里的"\+数字"就是用来代替数字所对应的第几个分组要在此处出现。

论坛徽章:
0
6 [报告]
发表于 2009-08-31 10:32 |只看该作者
发错了~~

[ 本帖最后由 iLRainyday 于 2009-8-31 10:37 编辑 ]

论坛徽章:
5
2015年辞旧岁徽章
日期:2015-03-03 16:54:152015年迎新春徽章
日期:2015-03-04 09:50:282015年亚洲杯之朝鲜
日期:2015-03-13 22:47:33IT运维版块每日发帖之星
日期:2016-01-09 06:20:00IT运维版块每周发帖之星
日期:2016-03-07 16:27:44
7 [报告]
发表于 2009-08-31 15:27 |只看该作者
先看正则基础吧。

论坛徽章:
0
8 [报告]
发表于 2012-10-22 15:28 |只看该作者
bequan 发表于 2009-08-30 22:47
明白了,back reference里的"\+数字"就是用来代替数字所对应的第几个分组要在此处出现。


正解!
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP