Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 39 ยท Strings, Dates and Regular Expressions

Regular Expressions in R: grepl, sub, gsub and regmatches

Search, test, replace and extract text with regular expressions in R: grepl, grep, sub, gsub, regexpr, gregexpr, regmatches, character classes, groups and lookaheads.

A regular expression (regex) is a compact pattern that describes a set of strings: "three digits, a dash, four digits" or "anything that looks like an email address". Once you can write patterns you can validate input, clean messy text and pull structured data out of free-form text with a line or two of code.

Base R ships a family of functions for this: grepl(), grep(), sub(), gsub(), regexpr(), gregexpr() and regmatches(). They all take the pattern as their first argument and the text vector second. If you have not yet met the basic string tools, start with R string basics.

The building blocks

Match one character

Literal cat matches cat
Dot . is any char
Class [0-9] or [[:digit:]]
Negated [^a-z] not a letter

In R strings, write backslashes twice: \d is written "\d".

1 / 3

Testing: grepl and grep

grepl() returns a logical vector (does each string match?). grep() returns the positions of the matches, or the matching strings with value = TRUE.

R
emails <- c("[email protected]", "bad.address", "[email protected]")

grepl("@", emails)                       # TRUE FALSE TRUE
grep("@", emails)                        # 1 3
grep("@", emails, value = TRUE)          # "[email protected]" "[email protected]"
grepl("^[[:alnum:]._-]+@[[:alnum:].-]+\\.[a-z]+$", emails)   # TRUE FALSE TRUE

The last pattern says: start of string, one or more letters/digits/dot/underscore/dash, an @, one or more letters/digits/dot/dash, a literal dot (\\.), letters, end of string. It is good enough to catch typos, though real email validation is better done by sending a message.

Useful options (they work in every function of this family): ignore.case = TRUE, fixed = TRUE (the pattern is plain text, much faster and no special characters), and perl = TRUE (use the PCRE engine, needed for lookaheads and \\d-style shortcuts in some situations).

Replacing: sub and gsub

sub() replaces the first match in each string; gsub() replaces all matches.

R
gsub("\\s+", " ", "a   b    c")                 # "a b c"
sub("a", "A", "banana")                          # "bAnana"
gsub("a", "A", "banana")                         # "bAnAnA"
gsub("[aeiou]", "", "education")                 # "dctn"
gsub("^\\s+|\\s+$", "", "  trim me  ")           # "trim me"

The replacement text can reuse what a group captured, through \\1, \\2 and so on:

R
sub("(\\w+) (\\w+)", "\\2 \\1", "hello world")   # "world hello"
gsub("(\\d{4})-(\\d{2})-(\\d{2})", "\\3/\\2/\\1", "2026-03-15")   # "15/03/2026"

perl = TRUE unlocks case conversion in the replacement: gsub("(^|\\s)(\\w)", "\\1\\U\\2", "the quick fox", perl = TRUE) returns "The Quick Fox".

Character classes and shortcuts

R supports two syntaxes. The POSIX classes always work inside brackets: [[:digit:]], [[:alpha:]], [[:alnum:]], [[:space:]], [[:upper:]], [[:lower:]], [[:punct:]]. The shortcut forms \\d (digit), \\w (letter, digit, underscore), \\s (whitespace) and their negations \\D, \\W, \\S are also accepted by the default engine, and \\b marks a word boundary in perl = TRUE mode.

Because R reads the string literal before the regex engine sees it, a backslash must be doubled: the regex \d+ is written "\\d+". A raw string avoids this: r"(\d+)".

R
grepl("^\\d+$", c("123", "12a", ""))             # TRUE FALSE FALSE
gsub("[^[:alnum:] ]", "", "Hi, there! (R)")      # "Hi there R"

Extracting: regexpr, gregexpr and regmatches

gsub() changes text; to pull matches out you pair a search function with regmatches(). regexpr() finds the first match per string, gregexpr() finds all of them.

R
x <- "Call 555-1234 or 555-9876"
m <- gregexpr("[0-9]{3}-[0-9]{4}", x)
regmatches(x, m)
# [[1]]
# [1] "555-1234" "555-9876"

regmatches(x, regexpr("[0-9]{3}-[0-9]{4}", x))   # "555-1234"

gregexpr() returns a list (one element per string) because the number of matches can differ per string. regmatches() combines the positions with the original text. A string without any match gives character(0) in the list.

Greedy versus lazy, and lookaheads

Quantifiers are greedy: they take as much text as they can. Add ? to make them lazy (needs perl = TRUE in some functions, but works in the default engine for *? and +? as well).

R
x <- "<b>bold</b> and <i>italic</i>"
sub("<.*>", "", x)         # "" (greedy: swallowed everything from the first < to the last >)
sub("<.*?>", "", x)        # "bold</b> and <i>italic</i>"
gsub("<.*?>", "", x)       # "bold and italic"

With perl = TRUE you also get lookarounds, which test the surroundings without consuming them:

R
gsub("(?<=\\d)(?=(\\d{3})+$)", ",", "1234567", perl = TRUE)   # "1,234,567"

This inserts a comma at every position that follows a digit and is followed by a multiple of three digits up to the end of the string.

A worked example: cleaning phone numbers

R
raw <- c("(555) 123-4567", "555.123.4567", "555 123 4567", "12345")

digits <- gsub("[^0-9]", "", raw)               # keep only digits
valid  <- nchar(digits) == 10
formatted <- ifelse(valid,
                    sub("(\\d{3})(\\d{3})(\\d{4})", "(\\1) \\2-\\3", digits),
                    NA)
formatted
# "(555) 123-4567" "(555) 123-4567" "(555) 123-4567" NA

Three small steps (strip, validate, reformat) are clearer than one giant pattern. Prefer that style when you write regexes: they are write-once, read-never if you make them too clever.

The same patterns in Python

Python's re module uses nearly the same syntax. Run this to see the same results. This is a comparison, not R.

Python Python comparison: the regex examples above

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Common mistakes

  • Single backslashes: "\d" is an error in R. Write "\\d" or use r"(\d)".
  • Swapping the argument order. It is grepl(pattern, x), the opposite of %in% habits.
  • Using . for a literal dot. Escape it ("\\.") or use fixed = TRUE.
  • Forgetting the anchors ^ and $, so "\\d+" accepts "12a".
  • Using sub() when you meant gsub().

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which function replaces every match, not just the first?

    gsub() is the global version; sub() stops after the first match in each string.
  2. 2. How do you write the regular expression \d+ inside an R string?

    R processes backslash escapes first, so a regex backslash must be doubled: "\d+" (or use the raw string r"(\d+)").
  3. 3. What does regmatches(x, gregexpr(pattern, x)) return?

    gregexpr() finds all matches per string and regmatches() extracts the text, one vector per input string, collected in a list.
  4. 4. Why does sub('<.*>', '', '<b>x</b>') remove the entire string?

    The greedy .* runs to the last > in the string. Use the lazy form <.*?> to stop at the first >.

Summary

  • grepl() tests, grep() finds positions or values, sub()/gsub() replace, regexpr()/gregexpr() + regmatches() extract.
  • Double every regex backslash in a normal string, or use a raw string.
  • Groups capture text that you can reuse as \\1, \\2 in replacements.
  • Quantifiers are greedy; add ? for lazy matching. Lookarounds need perl = TRUE.
  • Build patterns in small steps and anchor them with ^ and $.

Next: Dates and Times in R