Skip to main content
 首页 » 编程设计

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

2024年08月20日39dflying

我有以下 Python 正则表达式:

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

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

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

>>> p.search("I am in the the car.") 
 
<_sre.SRE_Match object; span=(8, 15), match='the the'> 

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

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

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

请您参考如下方法:

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

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group.

在使用反向引用时你无法避免使用组,但是你可以在整个模式周围放置一个新的组:

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