01 / 20
.*

Regular Expressions
in R Programming

Learn to match, find, and extract text patterns using regular expressions: the powerful pattern language built into R.

R Programming

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.

Pattern
A regex like "^[A-Z]" that describes what to match
Target
The text string you search through, e.g. "Hello World"

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.

Data Cleaning
Strip unwanted characters, standardize formats
Validation
Check if emails, phone numbers, or IDs follow a pattern
Extraction
Pull out zip codes, dates, or keywords from text

Anatomy of a Regex Pattern

^[A-Z][a-z]+\d{2,4}$ Anchor Start of string Character Class One uppercase letter Class + Quantifier One or more lowercase Shorthand + Quantifier 2 to 4 digits Anchor End of string ✓ Matches: "Hello2024"

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.

Literal Characters
Letters, digits, and most symbols match exactly. The pattern "cat" matches the text "cat" and nothing else.
Metacharacters
Symbols like . * + ? ^ $ [ ] ( ) { } | \ have special powers. The pattern "c.t" matches "cat", "cot", "c9t", etc.

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

1
Identify your goal. Are you checking, finding, extracting, or replacing?
2
Choose the R function. Use grepl() to check, grep() to find, sub()/gsub() to replace, regmatches() to extract.
3
Build the pattern. Start simple with literals, then add metacharacters as needed. Always test incrementally.
4
Remember double escaping. In R strings, write \\d (not \d), \\. (not \.), and \\\\ for a literal backslash.
5
Test on sample data. Use a small vector to verify matches before running on your full dataset.

Example 1: Checking with grepl()

Goal: Check which fruit names start with the letter "b" (case-insensitive).

# Create a vector of fruit names
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.

# Messy phone numbers
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 containing years
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":

Target string: C a l l _ 5 5 5 - 1 2 3 4 _ ... Match: "555-1234" Pattern: \d{3} 3 digits - literal dash \d{4} 4 digits

Character Classes Deep Dive

[abc]
Matches any one of the characters a, b, or c
[a-z]
Matches any lowercase letter from a through z
[^abc]
Matches anything except a, b, or c (negation)

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

✕ Single Backslash
Writing "\d" instead of "\\d". R strings need double backslashes because \ is an escape character in R too.
✕ Forgetting Anchors
Using "\\d{5}" without anchors matches 5 digits anywhere: "abc12345xyz" matches too.
✕ sub() vs gsub()
Using sub() when you want to replace all occurrences. sub() only replaces the first match. Use gsub() for all.

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?

Question 2 of 5

Which pattern matches a string that contains exactly three digits followed by a literal period?

Question 3 of 5

What is the output of gsub("[aeiou]", "*", "hello")?

Question 4 of 5

Why must you write "\\d" in R instead of "\d" to match a digit?

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?