gsub and sub
In this page:
gsub and sub
sub(pattern, replacement, x) replaces the first match of a pattern in a string, while gsub() replaces every match (the g stands for global). Both support regular expressions by default, making them powerful for pattern-based text transformation. This mirrors the relationship between sed's single and global replace modes.
Note: Use fixed = TRUE in sub()/gsub() when your pattern is a literal string, not a regex, to avoid special-character surprises.
Example: gsub and sub
text <- "cat bat cat sat"
cat(sub("cat", "dog", text), "\n")
cat(gsub("cat", "dog", text), "\n")
cat(gsub("[aeiou]", "*", text), "\n")
Login to try C/C++/Java/PHP code in the editor
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: