为什么sub()和gsub()具有相同的结果?

问题描述 投票:0回答:1
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"
r gsub
1个回答
0
投票

[使用模式".*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"

© www.soinside.com 2019 - 2024. All rights reserved.