Python正则表达式:findall()和search()

时间:2017-04-17 14:13:40

标签: python regex

我有以下Python正则表达式:

>>> p = re.compile(r"(\b\w+)\s+\1")

\b:字边界
\w+:一个或多个字母数字字符
\s+:一个或多个空格(可以是\t\n,..)
\1:对第1组的反向引用(= (..)之间的部分)

这个正则表达式应该找到一个单词的所有双重出现 - 如果两个出现的位置彼此相邻并且中间有一些空格。
使用搜索函数时,正则表达式似乎正常工作:

>>> p.search("I am in the the car.")

<_sre.SRE_Match object; span=(8, 15), match='the the'>

找到的匹配是the the,就像我预期的那样。奇怪的行为是在 findall 函数中:

>>> p.findall("I am in the the car.")

['the']

找到的匹配现在只有the。为什么不同?

1 个答案:

答案 0 :(得分:3)

在正则表达式中使用组时,findall()仅返回组;来自documentation

  

如果模式中存在一个或多个组,则返回组列表;如果模式有多个组,这将是一个元组列表。

在使用反向引用时,您无法避免使用组,但可以在整个模式中放置一个新组:

>>> p = re.compile(r"((\b\w+)\s+\2)")
>>> p.findall("I am in the the car.")
[('the the', 'the')]

外部组是第1组,因此反向引用应指向第2组。您现在有两个组,因此每个条目有两个结果。使用命名组可能会使其更具可读性:

>>> p = re.compile(r"((?P<word>\b\w+)\s+(?P=word))")

您可以将其过滤回外部组结果:

>>> [m[0] for m in p.findall("I am in the the car.")]
['the the']