Skip to main content
 首页 » 编程设计

python之使用捕获组提取字符串(使用 re.match)

2024年10月17日26arxive

这是我尝试检索 3 个捕获组的正则表达式

res = re.match("^(?![()]*)([()])(.*)$", input)

这是我的预期结果

input = "This is a ()demo)" 
I would need 3 capture groups  
res.group(1) -> "This is a " 
res.group(2) -> "(" 
res.group(3) -> ")demo)" 
 
input = "Another demo )(continues...()" 
res.group(1) -> "Another demo " 
res.group(2) -> ")" 
res.group(3) -> "(continues...()" 
 
input = "(last demo () and finally" 
res.group(1) -> "" 
res.group(2) -> "(" 
res.group(3) -> "last demo () and finally" 

但我编写的正则表达式与我上面给出的 3 个输入中的任何一个都不匹配。我在这里做错了什么?

请您参考如下方法:

您做错的第一件事是使用否定的先行断言

(?![()]*) 

我猜你是想说“匹配任何字符 except ()”。您可以通过以 ^ 符号开始组来对常规匹配组执行此操作。

([^()]*) 

否则,您的正则表达式几乎是正确的。

这是一个正则表达式,可以为您提供预期的输出

^([^()]*)([()])(.*)$ 

https://regex101.com/r/SD0L06/1