Python regex: findall() and search()



我有以下Python Regex:

>>> p = re.compile(r"(bw+)s+1")

b  : w+ :  一个或多个字母数字
s+ :  一个或多个whitespaces(可以是n1,..(
(..)   :   backReference to compt 1(= the the之间的零件(

此正则应该找到一个单词的所有双重事件 - 如果这两个事件彼此相邻,介于两者之间。
当使用搜索函数时,正则正则可以正常工作:

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

发现的匹配现在仅是findall()。为什么有区别?

在使用正则表达式中的组时,CC_11仅返回组;从文档中:

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

使用反向提示时,您无法避免使用组,但是您 can 将一个新组围绕整个模式:

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

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

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

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

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

最新更新