Search notes:
R functions: sub and gsub
The
sub
and
gsub
functions replace
regular expressions in character strings with a replacement text.
sub (regexp, txtReplace, vec); # Replace first occurence
gsub(regexp, txtReplace, vec); # Replace all occurences
text <- 'foo 42 bar 123 baz'
pattern <- '\\d+'
repl <- ''
sub(pattern, repl, text)
# [1] "foo bar 123 baz"
pattern <- '.*(\\d+).*'
repl <- '\\1'
sub(pattern, repl, text)
# [1] "3"
pattern <- '.* (\\d+).*'
repl <- '\\1'
sub(pattern, repl, text)
# [1] "123"
# non greedy:
pattern <- '.*? (\\d+).*'
repl <- '\\1'
sub(pattern, repl, text)
# [1] "42"
gsub("xyz", "bar", "foo xyz baz xyz")
# [1] "foo bar baz bar"
# Note the regular expression (^)
gsub("^xyz", "bar", "foo xyz baz abcxyz")
# [1] "foo xyz baz abcxyz"
gsub("xyz", "bar", c("foo", "xyz", "baz"))
# [1] "foo" "bar" "baz"