← Back to R Course | Chapter 6: Strings | Lesson 5 of 7

gsub and sub

In this page:

  1. gsub and sub

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

markup
text <- "cat bat cat sat"

cat(sub("cat", "dog", text), "\n")
cat(gsub("cat", "dog", text), "\n")
cat(gsub("[aeiou]", "*", text), "\n")
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.