str_replace不替换所有出现,但gsub呢?

时间:2017-12-01 13:02:13

标签: r string replace gsub stringr

我正在尝试删除字符串中的括号,如下所示。

library(stringr)

x <- "(Verhoeff,1937)"

str_replace(string = x, pattern = "(\\()|(\\))", replacement = "")
[1] "Verhoeff,1937)"

gsub(pattern = "(\\()|(\\))", replacement = "", x = x)
[1] "Verhoeff,1937"

str_replace似乎没有找到结束括号? 有什么想法吗?

1 个答案:

答案 0 :(得分:8)

它只匹配第一个出现,而gsub完成所有。请改用str_replace_all

str_replace(string = "aa", pattern = "a", replacement = "b") # only first

str_replace_all(string = "aa", pattern = "a", replacement = "b") # all