为什么这个模式不匹配?

2024-05-16 01:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

使用此模式:

(?<=\(\\\\).*(?=\))

这个主题字符串:'(\\Drafts) "/" "&g0l6P3ux-"'

我本来想匹配Drafts

然而,它不起作用。有人能解释为什么吗?你知道吗

我在Python中使用re模块,下面是我所做的:

>>> pattern = re.compile("(?<=\(\\\\).*?(?=\\))")
>>> pattern.pattern
'(?<=\\(\\\\).*?(?=\\))'
>>> two
'(\\Drafts) "/" "&g0l6P3ux-"'
>>> match = pattern.search(two)
>>> match
<_sre.SRE_Match object at 0x1096e45e0>
>>> match.groups()
()
>>> match.group(0)
'Drafts'
>>> 

我的问题是为什么groups什么也得不到,只有group得到正确的答案?你知道吗


Tags: 模块字符串re主题searchmatch模式group
1条回答
网友
1楼 · 发布于 2024-05-16 01:26:41

match.groups()为空,因为您的模式没有定义任何捕获组。match.group(0)是完全匹配的,而match.group(1)将是第一个捕获组(如果有)。你知道吗

为了提高可读性,应该将regex模式表示为原始字符串。你的可以写成

r"(?<=\(\\).*?(?=\))"

分解一下,有一个literal(\的lookback,然后是literal.*?,最后是literal)的lookahead。你知道吗

相关问题 更多 >