[英]Match parenthesis surrounded by spaces in python with regex
Why doesn't the following code block match the parantheses? 为什么下面的代码块不匹配括号?
In [27]: import re
In [28]: re.match('.*?([\(]*)', ' (((( ' ).groups()
Out[28]: ('',)
Demonstrating my comment: 展示我的评论:
import re
>>> re.match('.*?([\(]*)', ' (((( ' ).groups()
('',)
>>> re.match('.*?([\(]+)', ' (((( ' ).groups()
('((((',)
>>>
Note - you don't even need the backslash inside the []
- since special characters lose their meaning. 注意-您甚至不需要在
[]
使用反斜杠-因为特殊字符会失去其含义。 So 所以
>>> re.match('.*?([(]+)', ' (((( ' ).groups()
('((((',)
>>>
works too... 也可以...
This is because your "non greedy" first quantifier ( *?
) doesn't need to give anything to the second quantifier - since the second quantifier is happy with zero matches. 这是因为您的“非贪婪”第一个量词(
*?
)不需要为第二个量词提供任何内容-因为第二个量词对零匹配感到满意。
In your case .*?
就您而言
.*?
means everything because you used [\\(]*
which means 0 or more. So changing *
into +
will work for you as +
means 1 or more. 表示所有内容,因为您使用了
[\\(]*
表示0或更大。因此将*
更改为+
将为您工作,因为+
表示1或更大。
re.match('.*?([\(]+)', ' (((( ' ).groups()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.