gpt4 book ai didi

python - sub ('a*|b' , '' , 'bcd' ) -> bcd WAT?

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:04 25 4
gpt4 key购买 nike

今天我在正则表达式中偶然发现了一个奇怪的行为——匹配。我无法解释,尽管我认为我对正则表达式很有经验

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 替换。

关于python - sub ('a*|b' , '' , 'bcd' ) -> bcd WAT?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23769359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com