【发布时间】:2020-12-31 04:21:05
【问题描述】:
我在使用 python re 库时遇到了以下行为。
>>> import re
>>> re.sub(pattern=".*", repl="r", string="hello")
'rr'
如您所见,对于模式 .* 和替换字符 (r) re.sub 方法返回 rr。但我期待结果为r,因为.* 将匹配整个字符串。这是为什么?。我也在 Go 中测试了相同的逻辑,但它返回了预期的结果。
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`.*`)
fmt.Println(re.ReplaceAllString("Hello", "r")) // Will print `r`
}
【问题讨论】:
-
I cannot reproduce your observations,至少在 Python 中没有。投票结束是一个错字问题。
-
@TimBiegeleisen 我已经在 python 3.9(64 位)中测试了这个 sn-p
-
@TimBiegeleisen 似乎它在 3.6 中返回了正确的结果,但在 3.9 中却没有
-
这在 3.7 IIRC 版本中已更改,可能在某处存在正则表达式问题。有关详细信息,请参阅 regular-expressions.info/zerolength.html
标签: python regex replace python-re python-3.9