paulwinflo 发表于 2014-08-05 16:43

【求指点】字符串正则匹配问题

re.sub(r'(\b+) \1', r'\1', 'cat in the the hat')

参数里面2个“\1”不是很明白啥意思,大神能给我解释下么?为啥不用“\2”,小弟在这谢谢了!!

ssfjhh 发表于 2014-08-05 17:21

本帖最后由 ssfjhh 于 2014-08-05 17:22 编辑

In : re.sub(r'(\b+) \1', r'\1', 'cat cat in the the hat hat')
Out: 'cat in the hat'

yestreenstars 发表于 2014-08-05 17:37

\N表示对第N组小括号进行引用

paulwinflo 发表于 2014-08-06 10:25

回复 3# yestreenstars
>>re.sub(r'(\w+) (\b+) \2', r'\2', 'cat cat in the the hat hat')
>>'cat cat the hat hat'

   按照您的说法, 这里面\2是引用第二个括号内的。也就是(\b+),应该结果为'cat in the hat'为啥我运行后是 'cat cat the hat hat',你能详细说说么

paulwinflo 发表于 2014-08-06 10:26

回复 2# ssfjhh


    您能详细讲解下么,谢谢您了

ssfjhh 发表于 2014-08-06 10:31

回复 5# paulwinflo 'cat cat in the the hat hat'
'cat in the hat'上边一行是输入,下边一行是输入,很明显,这个正则是要去重呀。还不明白吗?

paulwinflo 发表于 2014-08-06 10:47

回复 6# ssfjhh


    我是对\n理解不太清楚?
页: [1]
查看完整版本: 【求指点】字符串正则匹配问题