Skip to content
Regex with grep, sub, gsub
step 1/5

Reading — step 1 of 5

Learn

~1 min readFunctional Patterns

R has rich regex support, mostly through 4 functions:

grep(pattern, x) — return INDICES of matches:

x <- c("apple", "banana", "cherry", "avocado")
grep("^a", x)              # c(1, 4)
grep("^a", x, value=TRUE)  # c("apple", "avocado")

grepl(pattern, x) — return LOGICAL vector:

grepl("^a", x)             # c(TRUE, FALSE, FALSE, TRUE)
x[grepl("^a", x)]          # filter to matches

sub(pattern, replacement, x) — replace first match:

sub("\\d+", "N", "file 123 size 456")    # "file N size 456"

gsub(pattern, replacement, x) — replace all matches:

gsub("\\d+", "N", "file 123 size 456")   # "file N size N"

Capture groups with backreferences \\1, \\2:

emails <- c("[email protected]", "[email protected]")
sub("^(.+)@(.+)$", "user=\\1 host=\\2", emails)
# "user=ada host=example.com"

Common pattern atoms (use \\ for backslash escapes since R strings interpret):

  • \\d — digit
  • \\w — word char
  • \\s — whitespace
  • ^, $ — anchors
  • [abc], [^abc] — char classes
  • *, +, ?, {n,m} — quantifiers

regmatches + regexpr for extracting matches:

m <- regmatches("phone: 555-1234", regexpr("\\d+-\\d+", "phone: 555-1234"))
m   # "555-1234"

For more complex parsing, packages like stringr provide consistent wrappers.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…