用正则表达式参考组内组

我试图找到一个正则表达式,将一个以两个相同的符号结尾的单词分组,后跟“ ter”并将其在两个符号上拆分。示例:“ Letter”一词应分为“ Let”和“ ter”。我正在使用python,这是到目前为止我得到的:


match = re.search(r'(\w*)((\w)\1(er$))', str)

print match.group(1) #should print 'Let'

print match.group(2) #should print 'ter'

问题在于(\ w)\ 1没有引用正确的组,因为它是组中的一个组。如何解决?


提前致谢。


千巷猫影
浏览 204回答 2
2回答

冉冉说

我正在使用命名组,因为这样可以更轻松地引用它们:import repattern = r"""&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; \b(?P<first_part>\w*(?P<splitter>\w))&nbsp; &nbsp;# matches starting at a word boundary&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; (?P<last_part>(?P=splitter)er\b)&nbsp; &nbsp; &nbsp; &nbsp; # matches the last letter of the first group&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # plus 'er' if followed by a word boundary&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; """matcher = re.compile(pattern, re.X)print matcher.search('letter').groupdict()# out: {'first_part': 'let', 'last_part': 'ter', 'splitter': 't'}

烙印99

我希望第一组是所有事物,直到并包括两个相同符号中的第一个,第二组是第二个相同符号后跟“ er”那将是:match = re.search(r'(\w*(\w)(?=\2))(\w*er$)', str)print match.groups()# -> ('Let', 't', 'ter')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python