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"
Github repository about-r, path: /functions/sub.R
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"
Github repository about-r, path: /functions/gsub.R

See also

Index to (some) R functions

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1758201039, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/R/functions/sub-gsub(79): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78