今天我在正则表达式中偶然发现了一个奇怪的行为——匹配。我无法解释,尽管我认为我对正则表达式很有经验
print re.sub('a*|b', '', 'bcd')
bcd
没有 glob 的地方
print re.sub('a|b', '', 'bcd')
cd
这是预期的。
我认为失败的替代方案不会阻止尝试其他方案!
请您参考如下方法:
a* 始终匹配(零到无限数量的 a 字符)。
因此,您最终在匹配位置替换了一个 '' 为 bcd。
所以整个字符串返回。
来自documentation :
re.sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl.
因此,'' 字符串的开头出现了零个 a,并被 repl 替换。
