Strings & Regular Expressions

Raw strings (R 4.0+): r"(C:\path\no\escapes)".

15.1 Base R strings

Raw strings (R 4.0+): r"(C:\path\no\escapes)".

s <- "Hello, World"
nchar(s)                               # 12
toupper(s); tolower(s); casefold(s, upper = TRUE)
substr(s, 1, 5)                        # "Hello"
strsplit("a,b,c", ",")[[1]]            # "a" "b" "c"
paste("a", "b", sep = "-")             # "a-b"
paste0("x", 1:3)                       # "x1" "x2" "x3"
paste(c("a", "b"), collapse = "+")     # "a+b"
sprintf("%s is %d years, %.2f m tall", "Ann", 30L, 1.68)
format(3.14159, nsmall = 2); format(1234567, big.mark = ",")
formatC(5, width = 3, flag = "0")      # "005"
trimws("  hi  ")
rev(strsplit("abc", "")[[1]])          # reverse characters
startsWith(s, "Hell"); endsWith(s, "ld")
sprintf("%5.1f%%", 12.345)
chartr("abc", "xyz", "aabbcc")
shQuote("it's"); dQuote("x", FALSE); noquote("text")
toupper(letters[1:3]); LETTERS; month.name
encodeString("a\nb"); enc2utf8(s); iconv(s, "UTF-8", "ASCII//TRANSLIT")

15.2 Regular expressions (base)

Regex essentials: . any char, ^/$ anchors, * + ? {n,m} quantifiers, [abc] classes, \\d \\w \\s (escape backslash in R strings!), ( ) groups, | alternation, (?i) case-insensitive, lookarounds with perl = TRUE.

x <- c("apple123", "banana", "cherry42")
grepl("[0-9]+", x)                      # TRUE FALSE TRUE
grep("an", x, value = TRUE)             # "banana"
sub("[0-9]+", "", x)                    # replace first match
gsub("a", "A", x)                       # replace all
regmatches(x, regexpr("[0-9]+", x))     # "123" "42"
regmatches(x, gregexpr("[a-z]", x))     # all matches
regexec("([a-z]+)([0-9]+)", "apple123") # capture groups
gsub("(\\w+)@(\\w+)", "\\2 at \\1", "me@host")   # backreferences
grepl("^a", x, ignore.case = TRUE); grepl(".", x, fixed = TRUE)
grepl("\\d+", x, perl = TRUE)           # PCRE

15.3 stringr (tidyverse) — consistent API

library(stringr)
str_length("hello")
str_to_upper("a"); str_to_title("hello world")
str_sub("hello", 1, 3)                    # "hel"
str_c("a", "b", sep = "-"); str_c(c("a", "b"), collapse = "")
str_detect(x, "\\d")                      # like grepl
str_subset(x, "an")
str_extract(x, "\\d+"); str_extract_all(x, "[a-z]")
str_match("apple123", "([a-z]+)(\\d+)")   # matrix with groups
str_replace(x, "a", "A"); str_replace_all(x, "[aeiou]", "_")
str_remove_all(x, "\\d")
str_split("a-b-c", "-", simplify = TRUE)
str_trim("  x  "); str_squish("  too   many   spaces ")
str_pad("7", 3, pad = "0")
str_count("banana", "a")                  # 3
str_starts(x, "b"); str_ends(x, "y")
str_glue("Name: {name}")                  # interpolation (also glue::glue)
str_wrap(long_text, width = 40)
str_sort(c("b", "a")); str_order(...)
str_view(x, "a+")                         # visualize matches
str_detect(x, regex("APPLE", ignore_case = TRUE))
str_detect(x, fixed("."))                 # literal match

15.4 glue — string interpolation

library(glue)
name <- "Ann"; n <- 3
glue("Hello {name}, you have {n} new message{ifelse(n == 1, '', 's')}.")