Regex/Python包含模式

2024-06-09 19:37:00 发布

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

我试着在网上研究这个问题的答案,但似乎没有什么能描述我在这里遇到的问题。如果我遗漏了什么,请关闭问题并将其重定向到已经回答的地方。你知道吗

也就是说,如果一个模式已经包含在另一个捕获的模式中,我的python regex似乎不想识别它。我尝试运行代码,结果如下:

>>> import re
>>> string = 'NNTSY'
>>> m = re.findall('N[^P][ST][^P]',string)
>>> m
['NNTS']

我不明白为什么它不能产生这样的结果:

>>> m
    ['NNTS','NTSY']

谢谢!你知道吗


Tags: 答案代码importrestring地方模式重定向
2条回答

re.findall(pattern, string, flags=0)

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. 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. Empty matches are included in the result unless they touch the beginning of another match.

https://docs.python.org/3/library/re.html#re.findall

如果您不只是想了解原因,而是真的需要获得重叠的匹配,您可以使用lookahead和捕获组,如in this question's answers所述。你知道吗

事实上,这是可能的,使用一个先行断言。你知道吗

(?=pattern)

将在任何位置直接匹配模式,而不消耗字符串,并且

(?=(pattern))

将捕获匹配的组。你知道吗

import re
string = 'NNTSY'
m = re.findall(r'(?=(N[^P][ST][^P]))',string)
print(m)
#['NNTS', 'NTSY']

相关问题 更多 >