This cheat sheet covers regular expression syntax for use in R, including character classes, anchors, quantifiers, and lookaheads, alongside the main base R functions (grep(), grepl(), sub(), gsub(), regexpr()) and their stringr equivalents (str_detect(), str_extract(), str_replace()). It also explains POSIX classes, PCRE-only features, greedy versus lazy matching, and case-insensitive mode.
What’s covered#
- Character classes – POSIX classes (
[[:digit:]],[[:alpha:]]),\\d,\\w,\\sand complements - Special characters – escape sequences
\n,\t,\r,\v,\f - Anchors and word boundaries –
^,$,\\b,\\B,\\<,\\> - Quantifiers –
*,+,?,{n},{n,m}; greedy vs. lazy with?and(?U) - Grouping and alternation –
(…),|,[…],[^…], back references - Lookahead and lookbehind –
(?=),(?!),(?<=),(?<!)(PCRE, requiresperl = TRUE) - Detect and locate –
grep(),grepl(),regexpr(),gregexpr(),str_detect(),str_locate() - Extract and replace –
regmatches(),str_extract(),str_match(),sub(),gsub(),str_replace()