Skip to main content
 首页 » 编程设计

python之为什么插入符号在正则表达式中与星号一起使用时不表现得贪婪

2025年02月15日28zfyouxi

我们都知道 * 表示 0 或更多,除非与 ? 等非贪婪运算符一起使用,否则它将始终尽可能贪婪。

>>> re.search('.*hello','hai hello there, hello again').group() 
'hai hello there, hello' 
>>> re.search('.*?hello','hai hello there, hello again').group() 
'hai hello' 

我刚看到下面的代码,对这种行为并不感到惊讶。

>>> re.search('\^*','abc^').group() 
'' 
>>> re.search('a*','abc^').group() 
'a' 

对于模式 \^*,我希望它与字符串中出现的一个脱字符相匹配。

但是,为什么它必须通过以 0 次出现插入符号和空字符串匹配退出来表现出非贪婪行为?

是因为 ^ 对正则表达式有特殊意义吗?如果是,那么我们如何将 ^ 与 * 符号匹配?

注意:当然,使用\^+作为模式,它显然会匹配字面插入符号。

请您参考如下方法:

正则表达式引擎从左到右解析输入字符串,因此,您的 \^* 匹配开头的空字符串,而 re.search 仅返回第一次出现的字符串.

搜索内容时,应避免使用可能匹配空字符串的模式,\^* 是匹配 0 个或多个 ^ 符号的模式。因此,最好的解决方案是使用 + 而不是 *。