请参阅Regex中的组内组

时间:2013-05-11 11:20:40

标签: python regex

我正在尝试找到一个正则表达式,该正则表达式将一个单词组合在两个相同的符号后面跟着“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没有引用正确的组,因为它是组内的一个组。这是怎么解决的?

提前致谢。

2 个答案:

答案 0 :(得分:6)

我正在使用命名组,因为它更容易引用它们:

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'}

答案 1 :(得分:1)

  

我希望第一组成为一切,直到并包括两个相同符号中的第一个,第二组是第二个相同的符号后跟'er'

那将是:

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

print match.groups()
# -> ('Let', 't', 'ter')
相关问题