可选,包含重新查找表达式的python组

2024-09-30 08:26:01 发布

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

我有一个正则表达式,它可以来自:

(src://path/to/foldernames canhave spaces/file.xzy)
(src://path/to/foldernames canhave spaces/file.xzy "optional string")

这些表达式出现在一个更长的字符串中(它们不是单独的字符串)。我在使用re.searchre.findall(因为字符串中可能有多个表达式)时无法匹配这两个表达式。在

单独匹配这两种情况都很简单,但是如何匹配两种情况,第一种返回src://path/...,第二种返回{}(如果存在),或者{}如果不存在呢?在

我认为我需要以某种方式指定或分组——例如,考虑:

模式\((.*)( ".*")\)匹配第二个实例,但不匹配第一个实例,因为它不包含"..."。在

^{pr2}$

While \((.*)( ".*")?\)与第一个组匹配,但在第二个实例中没有将{}单独标识为一个组。在

r = re.search(r'\((.*)( ".*")?\)', '(src://path/to/foldernames canhave spaces/file.xzy "optional string")')
r.groups()
('src://path/to/foldernames canhave spaces/file.xzy "optional string"', None)

有什么想法吗,你的表情大师(规则的变体)?在


Tags: topath实例字符串resrcsearchstring
2条回答

最简单的方法是使第一个*non-greedy

>>> import re
>>> string = "(src://path/to/foldernames canhave spaces/file.xzy)"
>>> string2 = \
... '(src://path/to/foldernames canhave spaces/file.xzy "optional string")'
>>> re.findall(r'\((.*?)( ".*")?\)', string2)
[('src://path/to/foldernames canhave spaces/file.xzy', ' "optional string"')]
>>> re.findall(r'\((.*?)( ".*")?\)', string)
[('src://path/to/foldernames canhave spaces/file.xzy', '')]

由于"通常不允许出现在文件名中,您可以简单地将它们从第一组中排除:

r = re.search(r'\(([^"]*)( ".*")?\)', input)

这通常是the preferred alternative to ungreedy repetition,因为它往往效率更高。如果由于某种原因,文件名实际上可以包含引号,那么不清晰的重复(如agf的答案)是最好的选择。在

相关问题 更多 >

    热门问题