【发布时间】:2020-06-19 13:17:52
【问题描述】:
我希望gsub 和stringr::str_replace_all 在下面返回相同的结果,但只有gsub 返回预期的结果。我正在开发一个课程来演示str_replace_all,所以我想知道为什么它在这里返回不同的结果。
txt <- ".72 2.51\n2015** 2.45 2.30 2.00 1.44 1.20 1.54 1.84 1.56 1.94 1.47 0.86 1.01\n2016** 1.53 1.75 2.40 2.62 2.35 2.03 1.25 0.52 0.45 0.56 1.88 1.17\n2017** 0.77 0.70 0.74 1.12 0.88 0.79 0.10 0.09 0.32 0.05 0.15 0.50\n2018** 0.70 0"
gsub(".*2017|2018.*", "", txt)
stringr::str_replace_all(txt, ".*2017|2018.*", "")
gsub 返回预期的输出(包括2017 之前和包括2018 之后和包括2018 的所有内容都已删除)。
gsub 的输出(预期)
[1] "** 0.77 0.70 0.74 1.12 0.88 0.79 0.10 0.09 0.32 0.05 0.15 0.50\n"
但是,str_replace_all 仅替换了 2017 和 2018,但保留了其余部分,即使两者使用了相同的 pattern。
str_replace_all 的输出(非预期)
[1] ".72 2.51\n2015** 2.45 2.30 2.00 1.44 1.20 1.54 1.84 1.56 1.94 1.47 0.86 1.01\n2016** 1.53 1.75 2.40 2.62 2.35 2.03 1.25 0.52 0.45 0.56 1.88 1.17\n** 0.77 0.70 0.74 1.12 0.88 0.79 0.10 0.09 0.32 0.05 0.15 0.50\n"
为什么会这样?
【问题讨论】:
标签: r regex stringr string-substitution