Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace doesn't replace all occurrences, but gsub does?

I am trying to remove brackets from a string like the one below.

library(stringr)

x <- "(Verhoeff,1937)"

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

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

str_replace doesn't seem to find the closing bracket? Any ideas why?

like image 561
zankuralt Avatar asked Dec 01 '17 13:12

zankuralt


1 Answers

It only matches the first occurency, whereas gsub does it all. Use str_replace_all instead:

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

str_replace_all(string = "aa", pattern = "a", replacement = "b") # all
like image 115
Tino Avatar answered Oct 17 '22 03:10

Tino