[英]"re.sub" method with ".*"
我正在使用 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`
}
下面應該開始解釋發生了什么:
>>> re.sub("x?", "_", "hello")
'_h_e_l_l_o_'
在字符串re.sub
中的每個 position 嘗試匹配x?
. 它成功了,因為x?
可以匹配空字符串,並用_
替換空字符串。
以類似的方式,在下面
>>> re.sub(".*", "r", "hello")
'rr'
我們有re.sub
嘗試匹配 position 0 中的.*
,成功並消耗了整個字符串。 然后它嘗試在末尾匹配 position,成功(匹配空字符串)並再次將其替換為r
。 如果您不允許空匹配,“令人費解”的行為就會消失:
>>> re.sub(".+", "r", "hello")
'r'
在 Python 3.7 之前的版本中,如果re.sub
消耗了整個字符串,它將不會再次嘗試匹配末尾,而在 Python 3.7+ 中它會。 更具體地說,引用re.sub
的文檔:
在 3.7 版更改:當與先前的非空匹配相鄰時,模式的空匹配將被替換。
>>> matches = lambda r, s: [m.span() for m in re.finditer(r, s)]
>>> matches("x?", "x")
[(0, 1), (1, 1)]
>>> matches("x?", "y")
[(0, 0), (1, 1)]
>>> re.sub("x?", "r", "x")
'rr'
>>> re.sub("x?", "r", "y")
'ryr
>>> matches("x?", "x")
[(0, 1), (1, 1)]
>>> matches("x?", "y")
[(0, 0), (1, 1)]
>>> re.sub("x?", "r", "x")
'r'
>>> re.sub("x?", "r", "y")
'ryr'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.