Python的问题关于芬德尔匹配变量时

2024-05-28 19:34:58 发布

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

我正在尝试匹配两个字符串变量,并希望捕获多个匹配项。关于芬德尔这似乎是这项任务的明显选择,但它似乎没有按照我期望的方式工作。以下是一个例子:

a = 'a(pp)?le'
b = 'ale, apple, apol'
match = re.findall(a,b)
match
['','pp']

但是,当我应用相同的变量时搜索,它识别字符串中嵌入的正则表达式,并获取第一个匹配项:

^{pr2}$

有人能解释一下为什么吗关于芬德尔在这种情况下不起作用?我预计会出现以下情况:

match = re.findall(a,b)
match
['ale','apple']

谢谢!在


Tags: 字符串releapplematch方式情况例子
2条回答

让我引用一下关于re.findall()Python docs

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.

这就是你的表达式a(pp)?le所做的。它与组中的内容相匹配,即pp。您可以通过使用非捕获组(?:...)来禁用组的这种特殊行为。在

您使用的是捕获组,而您需要的是非捕获组:

a = 'a(?:pp)?le'

如regex中的docs(...)中所述,将创建一个“捕获组”,并且关于芬德尔只会是帕伦斯家里的东西。在

如果您只想对事物进行分组(例如,为了应用?),请使用(?:...)来创建一个非捕获组。结果关于芬德尔在这种情况下将是整个regex(或最大的捕获组)。在

re.findall文档的关键部分是: 如果模式中存在一个或多个组,则返回组列表 这就解释了关于芬德尔以及搜索. 在

相关问题 更多 >

    热门问题