我试图找到一个正则表达式,它将一个单词组合在两个相同的符号后面跟着'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'
Run Code Online (Sandbox Code Playgroud)
问题是(\ w)\ 1没有引用正确的组,因为它是组内的一个组.这是怎么解决的?
提前致谢.
我正在使用命名组,因为它更容易引用它们:
import re
pattern = r"""
\b(?P<first_part>\w*(?P<splitter>\w)) # matches starting at a word boundary
(?P<last_part>(?P=splitter)er\b) # matches the last letter of the first group
# plus 'er' if followed by a word boundary
"""
matcher = re.compile(pattern, re.X)
print matcher.search('letter').groupdict()
# out: {'first_part': 'let', 'last_part': 'ter', 'splitter': 't'}
Run Code Online (Sandbox Code Playgroud)