我有一个正则表达式,它可以来自:
(src://path/to/foldernames canhave spaces/file.xzy)
(src://path/to/foldernames canhave spaces/file.xzy "optional string")
这些表达式出现在一个更长的字符串中(它们不是单独的字符串)。我在使用re.search
或re.findall
(因为字符串中可能有多个表达式)时无法匹配这两个表达式。在
单独匹配这两种情况都很简单,但是如何匹配两种情况,第一种返回src://path/...
,第二种返回{
我认为我需要以某种方式指定或分组——例如,考虑:
模式\((.*)( ".*")\)
匹配第二个实例,但不匹配第一个实例,因为它不包含"..."
。在
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)
有什么想法吗,你的表情大师(规则的变体)?在
最简单的方法是使第一个
*
non-greedy:由于
"
通常不允许出现在文件名中,您可以简单地将它们从第一组中排除:这通常是the preferred alternative to ungreedy repetition,因为它往往效率更高。如果由于某种原因,文件名实际上可以包含引号,那么不清晰的重复(如agf的答案)是最好的选择。在
相关问题 更多 >
编程相关推荐