TExcelTAD
Home › R › R Regular Expressions

R Regular Expressions

A regular expression (regex) is a pattern that describes text: "three digits", "a word that starts with a capital letter", "anything between brackets". R's pattern functions use them by default.

Function Returns
grepl(pattern, x) TRUE/FALSE for each element
grep(pattern, x) the positions of matching elements (value = TRUE for the elements)
sub(pattern, replacement, x) x with the first match replaced
gsub(pattern, replacement, x) x with all matches replaced
regmatches(x, regexpr(...)) the first matched text in each element
regmatches(x, gregexpr(...)) all matched texts (a list)

Pattern basics

Pattern Matches
. any character
[abc], [a-z], [^0-9] one of / range / not one of
\\d, \\w, \\s digit, word character, whitespace
^, $ start, end of the string
*, +, ? 0 or more, 1 or more, 0 or 1
{n}, {n,m} exactly n, between n and m
( ), | group, alternatives

In an R string, a backslash must itself be escaped, so the regex \d is written "\\d" (or r"(\d)" as a raw string).

r · try it yourself
codes <- c("AB-1234", "x-99", "CD-5678", "EF-12a4")
grepl("^[A-Z]{2}-\\d{4}
quot;, codes) grep("\\d{4}", codes) grep("\\d{4}", codes, value = TRUE)
[1]  TRUE FALSE  TRUE FALSE
[1] 1 3
[1] "AB-1234" "CD-5678"

Replacing text

r · try it yourself
phone <- c("(555) 123-4567", "555.987.6543")
gsub("[^0-9]", "", phone)                 # keep digits only
sub("\\s+
quot;, "", "trailing spaces ") gsub("(\\w+)@(\\w+)", "\\2 at \\1", "alice@example bob@test")
[1] "5551234567" "5559876543"
[1] "trailing spaces"
[1] "example at alice test at bob"

In the replacement, \\1, \\2, … refer to the text captured by the first, second, … group in parentheses.

Extracting matches

regexpr() finds the first match in each string, gregexpr() finds all of them, and regmatches() pulls out the text:

r · try it yourself
notes <- c("Order 1532 shipped", "No number here", "Refs 77 and 1204")
regmatches(notes, regexpr("[0-9]+", notes))
regmatches(notes, gregexpr("[0-9]+", notes))
[1] "1532" "77"
[[1]]
[1] "1532"

[[2]]
character(0)

[[3]]
[1] "77"   "1204"

The first call returns only the elements that matched, so it is shorter than the input. gregexpr() keeps one list element per input, which is empty when nothing matched.

Capture groups with regexec()

regexec() returns the full match and each group, which is perfect for parsing structured text:

r · try it yourself
log <- c("2024-03-14 ERROR disk full", "2024-03-15 INFO backup done")
m <- regmatches(log, regexec("^(\\d{4})-(\\d{2})-(\\d{2}) (\\w+) (.*)
quot;, log)) m[[1]] parsed <- do.call(rbind, lapply(m, function(g) g[-1])) colnames(parsed) <- c("year", "month", "day", "level", "message") parsed
[1] "2024-03-14 ERROR disk full" "2024"
[3] "03"                         "14"
[5] "ERROR"                      "disk full"
     year   month day  level   message
[1,] "2024" "03"  "14" "ERROR" "disk full"
[2,] "2024" "03"  "15" "INFO"  "backup done"

Options: case and fixed text

ignore.case = TRUE makes the match case-insensitive. fixed = TRUE switches regex off, so special characters like . and ( are taken literally, which is also faster:

r · try it yourself
grepl("error", c("Error!", "ERROR", "fine"), ignore.case = TRUE)
grepl(".", c("abc", "a.c"))               # . matches anything
grepl(".", c("abc", "a.c"), fixed = TRUE) # a literal dot
gsub("(", "[", "f(x)", fixed = TRUE)
[1]  TRUE  TRUE FALSE
[1] TRUE TRUE
[1] FALSE  TRUE
[1] "f[x)"

A practical example: validating emails

A simple (not RFC-complete) email check:

r · try it yourself
emails <- c("ana@mail.com", "bad@", "first.last@uni.edu", "no-at-sign.org")
pattern <- "^[[:alnum:]._-]+@[[:alnum:].-]+\\.[a-z]{2,}
quot; data.frame(email = emails, valid = grepl(pattern, emails))
               email valid
1       ana@mail.com  TRUE
2               bad@ FALSE
3 first.last@uni.edu  TRUE
4     no-at-sign.org FALSE

POSIX classes such as [:alnum:] (letters and digits), [:alpha:], [:digit:], [:space:] and [:punct:] must be written inside brackets: [[:digit:]].

Test yourself

How do you write the regex \d+ in a normal R string?

  1. "\d+"
  2. "\\d+"
  3. "/d+"
  4. "d+"

What does sub("o", "0", "foo") return?

  1. "f00"
  2. "f0o"
  3. "foo"
  4. "0oo"

Which argument makes . in a pattern match only a literal dot?

  1. literal = TRUE
  2. fixed = TRUE
  3. perl = TRUE
  4. escape = TRUE