R Regular Expressions
A regular expression (regex) is a pattern that describes a set of strings. Instead of searching for an exact word, regex lets you search for patterns — "any 10-digit number", "any email address", "any word starting with A". R uses regex with functions like grepl(), gsub(), and regexpr().
Basic Pattern Building Blocks
Pattern Meaning Example
────────────────────────────────────────────────────────────
. Any single character "c.t" matches "cat","cut","c9t"
* Previous item zero or more times "go*" matches "g","go","goo"
+ Previous item one or more times "go+" matches "go","goo"
? Previous item zero or one time "colou?r" matches "color","colour"
^ Start of string "^R" matches "R is fun"
$ End of string "csv$" matches "data.csv"
[abc] One of these characters "[aeiou]" any vowel
[^abc] None of these characters "[^0-9]" any non-digit
[a-z] Range of characters "[a-z]" lowercase letter
\\d Digit (0-9) "\\d{3}" three digits
\\D Non-digit
\\w Word character (letter/digit/_)
\\s Whitespace
Quantifiers
{n} Exactly n times "\\d{4}" → exactly 4 digits
{n,} At least n times "\\d{2,}" → 2 or more digits
{n,m} Between n and m times "\\d{2,4}" → 2 to 4 digits
grepl() — Pattern Matching
# Check if emails are valid (simplified pattern)
emails <- c("user@example.com", "badEmail", "test@domain.org", "noatsign")
valid <- grepl("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", emails)
print(valid)
# TRUE FALSE TRUE FALSE
Practical Regex Patterns
Pattern What It Matches
────────────────────────────────────────────────────────────
"^\\d{10}$" Exactly 10 digits (phone number)
"^[A-Z]{2}\\d{6}$" 2 uppercase + 6 digits (passport ID)
"\\d{1,2}/\\d{1,2}/\\d{4}" Date in DD/MM/YYYY format
"^[A-Za-z ]+$" Only letters and spaces
"[0-9]+(\\.[0-9]+)?" Integer or decimal number
"\\b\\w{5}\\b" Exactly 5-letter words
gsub() and sub() — Replace with Regex
# Remove all non-numeric characters
messy <- "Phone: (91) 98765-43210"
clean <- gsub("[^0-9]", "", messy)
# "919876543210"
# Remove extra whitespace
text <- "Too many spaces here"
clean <- gsub("\\s+", " ", text)
# "Too many spaces here"
# Mask email domain for privacy
email <- "user@private.com"
masked <- gsub("@.*$", "@***", email)
# "user@***"
regmatches() — Extract Matches
text <- "Call us at 9876543210 or 8765432109 for help"
matches <- regmatches(text, gregexpr("\\d{10}", text))[[1]]
print(matches)
# "9876543210" "8765432109"
Groups and Capture with regmatches
# Extract date parts
dates <- c("15/08/2024", "01/01/2025", "25/12/2024")
pattern <- "(\\d{2})/(\\d{2})/(\\d{4})"
m <- regmatches(dates, regexec(pattern, dates))
m[[1]] # "15/08/2024" "15" "08" "2024"
Real Use Case: Validate and Extract PIN Codes
addresses <- c(
"12 MG Road, Bengaluru 560001",
"45 Park Street, Kolkata 700016",
"No PIN here",
"Chennai 600001"
)
# Check if PIN code present (6 digits)
has_pin <- grepl("\\b[1-9][0-9]{5}\\b", addresses)
print(has_pin)
# TRUE TRUE FALSE TRUE
# Extract PIN codes
pins <- regmatches(addresses, regexpr("\\b[1-9][0-9]{5}\\b", addresses))
print(pins)
# "560001" "700016" "600001"
Quick Reference: Common Anchors and Groups
^ start of string
$ end of string
\\b word boundary (between word char and non-word char)
( ) grouping and capture
| OR ("cat|dog" matches "cat" or "dog")
(?i) case-insensitive (in Perl regex: perl=TRUE)
Regular expressions are one of the most powerful text-processing tools in programming. A single regex line can validate thousands of email addresses, extract all phone numbers from a document, or clean an entire column of messy text. Start with simple patterns and build up gradually — each new pattern you learn dramatically expands what you can do with text data.
