R regular expressions
last modified November 19, 2026
A regular expression is a pattern that describes a set of strings.
Instead of comparing text character by character, R matches the pattern
against the whole string or against a part of it, which makes it possible to
find, extract, replace, and split text whose exact content is not known in
advance. Base R uses the functions grep, grepl,
sub, gsub, regexpr, and
gregexpr for this work. This article covers the pattern syntax
that those functions share, capture groups, replacements, and the PCRE engine
that is enabled with perl = TRUE.
Detecting a match
grepl returns a logical vector with one value per input string,
while grep returns the positions of the strings that match. Both
accept value = TRUE, which makes grep return the
matching strings themselves instead of their positions.
emails <- c("ada@example.com", "grace@sample.org", "not-an-email")
print(grepl("@", emails))
print(grep("@", emails))
print(grep("@", emails, value = TRUE))
The at sign is a literal character in a regular expression, so the pattern
simply looks for it anywhere in the string. Two of the three strings contain
it. grepl is the form to use inside a logical condition, because
it returns a vector that can index a data frame; grep is more
convenient when the positions or the values are wanted directly.
$ Rscript detecting.R [1] TRUE TRUE FALSE [1] 1 2 [1] "ada@example.com" "grace@sample.org"
Anchors, classes, and wildcards
A pattern is not automatically anchored to the start or the end of a string.
The caret ^ matches the start, the dollar sign $
matches the end, and [0-9] matches one digit. A quantifier such
as {3} repeats the previous element exactly three times, and the
dot . matches any single character.
codes <- c("R-101", "R-250", "PY-101", "R-1")
print(grep("^R-", codes, value = TRUE))
print(grep("[0-9]{3}$", codes, value = TRUE))
print(grep("R.1", codes, value = TRUE))
print(grep("R.1", codes, value = TRUE, fixed = TRUE))
The first pattern keeps every code that starts with R-, and the second keeps
every code that ends with three digits, which includes PY-101. Anchoring only
one end is therefore not enough to describe a whole code. The dot in
R.1 matches the hyphen and finds two codes, while
fixed = TRUE treats the dot literally and finds none.
$ Rscript anchors.R [1] "R-101" "R-250" "R-1" [1] "R-101" "R-250" "PY-101" [1] "R-101" "R-1" character(0)
Extracting the match
regexpr finds the first match in each string and returns its
start position, with the match length stored in an attribute. A value of minus
one means that the string did not match. regmatches turns the
positions back into the matched text.
text <- c("order 12", "order 7", "none")
where <- regexpr("[0-9]+", text)
print(where)
print(regmatches(text, where))
The first two strings match at position seven, and the third returns minus
one. regmatches keeps only the strings that matched, so its
result has two elements rather than three. The position counts characters;
the useBytes attribute records whether byte positions were used
instead, which matters for non-ASCII text.
$ Rscript extracting.R [1] 7 7 -1 attr(,"match.length") [1] 2 1 -1 attr(,"index.type") [1] "chars" attr(,"useBytes") [1] TRUE [1] "12" "7"
Replacing text
sub replaces the first match in each string, and
gsub replaces every match. The replacement is ordinary text and
may contain backreferences to capture groups. Both functions return a new
character vector and leave the input unchanged.
text <- c("red apple", "red red rose")
print(sub("red", "blue", text))
print(gsub("red", "blue", text))
The first string contains one red, so both functions produce the same result
for it. The second string contains red twice, and only gsub
replaces both occurrences. Use sub when only the first occurrence
is meant, and gsub when the pattern describes a token that may
repeat.
$ Rscript replacing.R [1] "blue apple" "blue red rose" [1] "blue apple" "blue blue rose"
Capture groups
Parentheses around part of a pattern create a capture group. The
groups are numbered from left to right, and the replacement can refer to them
as \1, \2, and so on. In an R string literal each
backslash must be doubled, so the replacement is written "\\1".
dates <- c("19/11/2026", "01/01/2027")
print(sub("([0-9]{2})/([0-9]{2})/([0-9]{4})", "\\3-\\2-\\1", dates))
print(gsub("([a-z]+)@([a-z]+)", "\\2 at \\1", c("ada@example", "grace@sample")))
The first pattern splits a date into day, month, and year and rebuilds it in ISO order. The second pattern moves the domain in front of the user name. The groups make the replacement independent of the actual digits and letters, which is what separates a rewrite from a plain substitution.
$ Rscript captures.R [1] "2026-11-19" "2027-01-01" [1] "example at ada" "sample at grace"
Splitting with patterns
strsplit accepts a regular expression as its separator, so one
call can split at a run of digits rather than at one fixed character. The
function gregexpr finds every match in a string and returns all
positions, which regmatches converts into the matched pieces.
line <- "a1b22c333"
print(strsplit(line, "[0-9]+")[[1]])
print(regmatches(line, gregexpr("[0-9]+", line))[[1]])
The pattern [0-9]+ matches one or more digits, so the string is
cut at every number and only the letters remain. gregexpr works
the other way round and collects the numbers themselves. Runs of different
lengths are handled by the plus sign, which is the difference between
+ and a fixed repetition such as {3}.
$ Rscript splitting.R [1] "a" "b" "c" [1] "1" "22" "333"
The PCRE engine
Base R uses the TRE engine by default. The argument perl = TRUE
switches to PCRE, which supports lookarounds and other constructs that TRE
does not. A lookbehind such as (?<=R-) matches a
position without consuming the text before it.
codes <- c("R-101", "PY-250", "R-7")
print(grepl("(?<=R-)[0-9]+", codes, perl = TRUE))
print(grepl("^R-[0-9]+$", codes))
print(regmatches(codes, regexpr("(?<=R-)[0-9]+", codes, perl = TRUE)))
The lookbehind requires the letters R- before the digits but keeps them out
of the match, so regmatches returns only 101 and 7. The same
pattern without perl = TRUE is rejected as an invalid regular
expression. Use PCRE when a pattern needs lookarounds or named groups, and
keep the default engine for portable patterns that do not.
$ Rscript perl.R [1] TRUE FALSE TRUE [1] TRUE FALSE TRUE [1] "101" "7"
A complete example
The next script cleans a vector of addresses and checks their shape. It lowercases the text, trims the spaces, and applies an anchored pattern that requires letters, an at sign, a domain, a literal dot, and a suffix of at least two letters. The result is a small data frame with the original and the cleaned address side by side.
raw <- c(" Ada@Example.COM ", "grace@sample.org", "bad@@example")
clean <- trimws(tolower(raw))
valid <- grepl("^[a-z]+@[a-z]+\\.[a-z]{2,}$", clean)
print(data.frame(raw, clean, valid))
The third address fails because it contains two at signs, so its
valid value is false. The pattern is deliberately simple: a full
email validator is much longer, and in practice the only reliable check is to
send a message. The example still shows the usual workflow of normalising the
text first and validating the result second.
$ Rscript cleaning.R
raw clean valid
1 Ada@Example.COM ada@example.com TRUE
2 grace@sample.org grace@sample.org TRUE
3 bad@@example bad@@example FALSE
Next steps
The strings article covers the fixed-position operations that this article replaces with patterns, and the dates and times article parses the date strings that the capture example rewrites. The stringr article later in the series wraps the same ideas in a consistent set of verbs.
Source
R documentation: regular expressions as used in R
R documentation: pattern matching and replacement
In this article we have detected matches with grepl and
grep, anchored patterns with ^ and $,
and used character classes, quantifiers, and wildcards. We extracted the
matched text with regexpr and regmatches, replaced
it with sub and gsub, and rewrote strings through
capture groups. We split at patterns, enabled PCRE for a lookbehind, and
validated a small list of addresses. The series continues with
R dates and times.
Author
List all R Language tutorials.