x <- c("This is a sentence about axis",
"A second pattern is also listed here")
sub(".*is", "XY", x)
#[1] "XY" "XYted here"
gsub(".*is", "XY", x)
#[1] "XY" "XYted here"
[使用模式".*is"
时,它匹配从字符串开头到最后一个"is"
的所有内容,第一句中的内容是"is"
中的"axis"
和第二个字符串中的"is"
中的"listed"
。因此,直到该部分的所有内容都被"XY"
替换。
您可能期望的是:
sub("is", "XY", x)
#[1] "ThXY is a sentence about axis" "A second pattern XY also listed here"
gsub("is", "XY", x)
#[1] "ThXY XY a sentence about axXY" "A second pattern XY also lXYted here
如您在sub
调用中看到的,仅第一个"is"
被替换,而在gsub
中,"is"
的所有实例都被替换为"XY"
。