Regular Expressions
in R Programming
Learn to match, find, and extract text patterns using regular expressions: the powerful pattern language built into R.
What Are Regular Expressions?
A regular expression (or regex) is a sequence of characters that defines a search pattern. Think of it as a mini-language for describing text: instead of searching for an exact word, you describe the shape of what you are looking for.
Why Regex Matters in R
Real-world data is messy. Dates come in mixed formats, names have inconsistent capitalization, and columns contain embedded codes. Regex lets you clean, validate, and extract information from text at scale.
Anatomy of a Regex Pattern
Core Building Blocks
| Symbol | Meaning | Example |
|---|---|---|
| . | Any single character | "c.t" matches "cat", "cut" |
| * | Zero or more of previous | "ab*c" matches "ac", "abc", "abbc" |
| + | One or more of previous | "ab+c" matches "abc", "abbc" (not "ac") |
| ? | Zero or one of previous | "colou?r" matches "color", "colour" |
| ^ / $ | Start / end of string | "^Hi" matches "Hi there" (not "Say Hi") |
| [abc] | Any character in set | "[aeiou]" matches any vowel |
| \d | Any digit (0-9) | "\d{3}" matches "415", "123" |
Literal vs Metacharacter
The most fundamental distinction in regex: some characters match themselves (literals), while others have special meaning (metacharacters). Confusing the two is the most common source of errors.
R's Key Regex Functions
| Function | Returns | Purpose |
|---|---|---|
| grepl() | TRUE / FALSE | Does pattern match? |
| grep() | Indices or values | Which elements match? |
| sub() | Modified string | Replace first match |
| gsub() | Modified string | Replace all matches |
| regmatches() | Matched text | Extract matched portions |
How to Apply Regex in R
Example 1: Checking with grepl()
Goal: Check which fruit names start with the letter "b" (case-insensitive).
fruits <- c("apple", "banana", "Blueberry", "cherry")
# Check which start with "b" (ignore case)
grepl("^b", fruits, ignore.case = TRUE)
# [1] FALSE TRUE TRUE FALSE
Example 2: Replacing with gsub()
Goal: Clean phone numbers by removing all non-digit characters.
phones <- c("(415) 555-1234", "650.555.5678")
# Remove everything that is NOT a digit
gsub("[^0-9]", "", phones)
# [1] "4155551234" "6505555678"
Example 3: Extracting with regmatches()
Goal: Extract all 4-digit years from a text string.
text <- "Founded in 1776, rebuilt in 1812 and 2001."
# Find positions of 4-digit sequences
matches <- gregexpr("\\d{4}", text)
# Extract the matched text
regmatches(text, matches)
# [[1]]
# [1] "1776" "1812" "2001"
How Matching Works
The regex engine scans left-to-right, trying to match the pattern at each position. Here is "\d{3}-\d{4}" matching against "Call 555-1234 today":
Character Classes Deep Dive
Quantifiers: How Many?
| Quantifier | Meaning | Matches |
|---|---|---|
| * | 0 or more | "", "a", "aa", "aaa", ... |
| + | 1 or more | "a", "aa", "aaa", ... (not "") |
| ? | 0 or 1 | "", "a" (at most one) |
| {n} | Exactly n | "aaa" when n=3 |
| {n,m} | Between n and m | "aa", "aaa" when n=2, m=3 |
| {n,} | n or more | "aa", "aaa", ... when n=2 |
Common Mistakes
Quick Reference Summary
| Task | Function | Example Pattern |
|---|---|---|
| Does it match? | grepl() | "^[A-Z]" |
| Find indices | grep() | "error" |
| Replace first | sub() | "\\s+" → " " |
| Replace all | gsub() | "[^a-z]" → "" |
| Extract text | regmatches() | "\\d{4}" |
| Match a period | Any | "\\." (escaped) |
| Any character | Any | "." (unescaped) |
Question 1 of 5
What does the R function grepl("^A", x) return?
grepl() always returns a logical vector (TRUE/FALSE) indicating which elements match the pattern. The ^ anchor means "starts with", so "^A" checks if each element begins with the letter "A".Question 2 of 5
Which pattern matches a string that contains exactly three digits followed by a literal period?
\\d{3} matches exactly three digits, and \\. matches a literal period (escaped because . is a metacharacter). Options A and B use an unescaped . which matches any character. Option D uses parentheses instead of curly braces.Question 3 of 5
What is the output of gsub("[aeiou]", "*", "hello")?
gsub() replaces all matches. The pattern [aeiou] matches any vowel. In "hello", the vowels are e (position 2) and o (position 5). Both are replaced with "*", giving "h*ll*".Question 4 of 5
Why must you write "\\d" in R instead of "\d" to match a digit?
\) is an escape character in strings (e.g., \n = newline). To get a literal backslash into the regex pattern, you must write \\ in the R string. So "\\d" sends the pattern \d to the regex engine.Question 5 of 5
You want to check if elements in a vector start with a capital letter and end with a digit. Which R call is correct?
grepl() returns TRUE/FALSE for checking. ^[A-Z] anchors to the start and requires a capital letter. .* allows any characters in between. \\d$ requires a digit at the end. Option A uses grep() (returns indices, not logical). Option B lacks anchors. Option C matches lowercase, not uppercase.