Work with strings with stringr : : CHEAT SHEETThe stringr package provides a set of internally consistent tools for working with character strings, i.e. sequences of characters surrounded by quotation marks.

Detect Matches

Subset Strings

str_detect(string, pattern) Detect thepresence of a pattern match in a string.
str_detect(fruit, "a")str_sub(string, start = 1L, end = -1L) Extract
substrings from a character vector.
str_sub(fruit, 1, 3); str_sub(fruit, -2)

124

str_which(string, pattern) Find the indexes ofstrings that contain a pattern match.
str_which(fruit, "a")str_subset(string, pattern) Return only thestrings that contain a pattern match.
str_subset(fruit, "b")str_pad(string, width, side = c("left", "right","both"), pad = " ") Pad strings to constantwidth. str_pad(fruit, 17)

0
3
1
2

str_count(string, pattern) Count the numberof matches in a string.
str_count(fruit, "a")str_extract(string, pattern) Return the firstpattern match found in each string, as a vector.
Also str_extract_all to return every patternmatch. str_extract(fruit, "[aeiou]")

str_trunc(string, width, side = c("right", "left","center"), ellipsis = "...") Truncate the width ofstrings, replacing content with ellipsis.
str_trunc(fruit, 3)

str_match(string, pattern) Return the firstpattern match found in each string, as amatrix with a column for each ( ) group inpattern. Also str_match_all.
str_match(sentences, "(a|the) ([^ ]+)")

str_trim(string, side = c("both", "left", "right"))
Trim whitespace from the start and/or end of astring. str_trim(fruit)

TRUETRUEFALSE
TRUE

start end

2 44 7NA NA
3 4

str_locate(string, pattern) Locate thepositions of pattern matches in a string. Also
str_locate_all. str_locate(fruit, "a")Mutate Strings

NANA NA

Join and Split
str_c(..., sep = "", collapse = NULL) Join
multiple strings into a single string.
str_c(letters, LETTERS)

str_sub() <- value. Replace substrings byidentifying the substrings with str_sub() andassigning into the results.
str_sub(fruit, 1, 3) <- "str"a string
A STRING
a string
A String

str_split_fixed(string, pattern, n) Split avector of strings into a matrix of substrings(splitting at occurrences of a pattern match).
Also str_split to return a list of substrings.
str_split_fixed(fruit, " ", n=2)

str_to_lower(string, locale = "en")1 Convert
strings to lower case.
str_to_lower(sentences)
str_to_upper(string, locale = "en")1 Convert
strings to upper case.
str_to_upper(sentences)
str_to_title(string, locale = "en")1 Convert
strings to title case. str_to_title(sentences)

{xx}

{yy}

glue::glue(..., .sep = "", .envir =parent.frame(), .open = "{", .close = "}") Createa string from strings and {expressions} toevaluate. glue::glue("Pi is {pi}")glue::glue_data(.x, ..., .sep = "", .envir =parent.frame(), .open = "{", .close = "}") Use adata frame, list, or environment to create astring from strings and {expressions} toevaluate. glue::glue_data(mtcars,"{rownames(mtcars)} has {hp} hp")

str_length(string) The width of strings (i.e.
number of code points, which generally equals
the number of characters). str_length(fruit)

Order Strings
41
32

str_order(x, decreasing = FALSE, na_last =TRUE, locale = "en", numeric = FALSE, ...)1 Returnthe vector of indexes that sorts a character
vector. x[str_order(x)]str_sort(x, decreasing = FALSE, na_last = TRUE,locale = "en", numeric = FALSE, ...)1 Sort acharacter vector.
str_sort(x)str_dup(string, times) Repeat strings times
times. str_dup(fruit, times = 2)

str_replace_all(string, pattern,replacement) Replace all matched patterns
in each string. str_replace_all(fruit, "a", "-")
a string

462
3

str_c(..., sep = "", collapse = NULL) Collapse avector of strings into a single string.
str_c(letters, collapse = "")str_replace(string, pattern, replacement)
Replace the first matched pattern in eachstring. str_replace(fruit, "a", "-")A STRING

Manage Lengths

Helpers

str_conv(string, encoding) Override theencoding of a string. str_conv(fruit,"ISO-8859-1")
str_view(string, pattern, match = NA) View
HTML rendering of first regex match in eachstring. str_view(fruit, "[aeiou]")
str_view_all(string, pattern, match = NA) View
HTML rendering of all regex matches.
str_view_all(fruit, "[aeiou]")
str_wrap(string, width = 80, indent = 0, exdent= 0) Wrap strings into nicely formatted
paragraphs. str_wrap(sentences, 20)
1 See bit.ly/ISO639-1 for a complete list of locales.

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at stringr.tidyverse.org • Diagrams from @LVaudor ! • stringr 1.2.0 • Updated: 2017-10expressions, or regexps, are a concise language forRegular Expressions - Regulardescribing patterns in strings.

Pattern arguments in stringr are interpreted as
regular expressions after any special charactershave been parsed.

MATCH CHARACTERS

In R, you write regular expressions as strings,
sequences of characters surrounded by quotes("") or single quotes('').
Some characters cannot be represented directlyin an R string . These must be represented as
special characters, sequences of characters thathave a specific meaning., e.g.
Special Character Represents\\\"\n\"new lineRun ?"'" to see a complete list
Because of this, whenever a \ appears in a regularexpression, you must write it as \\ in the stringthat represents the regular expression.
Use writeLines() to see how R views your string
after all special characters have been parsed.
writeLines("\\.")# \.
writeLines("\\ is a backslash")# \ is a backslash

INTERPRETATION
Patterns in stringr are interpreted as regexs Tochange this default, wrap the pattern in one of:regex(pattern, ignore_case = FALSE, multiline =FALSE, comments = FALSE, dotall = FALSE, ...)
Modifies a regex to ignore cases, match end oflines as well of end of strings, allow R comments
within regex's , and/or to have . match everything
including \n.
str_detect("I", regex("i", TRUE))
fixed() Matches raw bytes but will miss somecharacters that can be represented in multiple
ways (fast). str_detect("\u0130", fixed("i"))string (type regexpthis)(to mean this)

\\.
\\!
\\?
\\\\
\\(\\)\\{\\}\\n\\t\\s\\d\\w\\ba (etc.)\.
\!
\?
\\\(\)\{\}\n\t\s\d\w\b1[:digit:]1[:alpha:]1[:lower:]
1[:upper:]1[:alnum:][:punct:] 1[:graph:] 1[:space:] 1[:blank:] 1.

see <- function(rx) str_view_all("abc ABC 123\t.!?\\(){}\n", rx)
matches(which matches this)examplea (etc.)
.
!
?
\()
{}
new line (return)tab
any whitespace (\S for non-whitespaces)
any digit (\D for non-digits)
any word character (\W for non-word chars)word boundaries
digitsletters
lowercase letters
uppercase lettersletters and numberspunctuation
letters, numbers, and punctuation
space characters (i.e. \s)space and tab (but not new line)
every character except a new linesee("a")see("\\.")
see("\\!")
see("\\?")
see("\\\\")
see("\\(")
see("\\)")
see("\\{")see( "\\}")
see("\\n")see("\\t")see("\\s")see("\\d")see("\\w")see("\\b")see("[:digit:]")see("[:alpha:]")see("[:lower:]")see("[:upper:]")see("[:alnum:]")see("[:punct:]")see("[:graph:]")see("[:space:]")see("[:blank:]")see(".")[:blank:]
space

abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}
abc ABC 123 .!?\(){}.

tab[:graph:][:punct:]. , : ; ? ! \ | / ` = * + - ^_ ~ " ' [ ] { } ( ) < > @# $[:alnum:][:digit:]0 1 2 3 4 5 6 7 8 9[:alpha:][:lower:][:upper:]a b c d e f

A B CD E F

g h i j k l

GH I J K L

mn o p q r

MNO PQ Rs t u vw x

S TU V WXzZ1 Many base R functions require classes to be wrapped in a second set of [ ], e.g. [[:digit:]]alt <- function(rx) str_view_all("abcde", rx)

ALTERNATES
regexpmatches

exampleab|d[abe][^abe][a-c]or
one ofanything but
range

alt("ab|d")alt("[abe]")alt("[^abe]")alt("[a-c]")

abcde
abcde
abcde
abcde

anchor <- function(rx) str_view_all("aaa", rx)

ANCHORScoll() Matches raw bytes and will use locale
specific collation rules to recognize charactersthat can be represented in multiple ways (slow).
str_detect("\u0130", coll("i", TRUE, locale = "tr"))boundary() Matches boundaries between
characters, line_breaks, sentences, or words.
str_split(sentences, boundary("word"))[:space:]new line"

Need to Know

regexpmatches

example^aa$

start of string
end of stringanchor("^a")anchor("a$")

aaa
aaa

quant <- function(rx) str_view_all(".a.aa.aaa", rx)

QUANTIFIERS

1 2 ... n
1 2 ... nn ... mregexpmatches

examplea?
a*a+a{n}a{n, }
a{n, m}zero or one
zero or moreone or moreexactly nn or more
between n and mquant("a?")quant("a*")quant("a+")quant("a{2}")quant("a{2,}")quant("a{2,4}")

ref <- function(rx) str_view_all("abbaab", rx)

GROUPS

Use parentheses to set precedent (order of evaluation) and create groups
regexp(ab|d)elook <- function(rx) str_view_all("bacad", rx)

LOOK AROUNDS
regexpmatches

examplea(?=c)a(?!c)(?<=b)a(?<!b)afollowed by
not followed bypreceded by
not preceded bylook("a(?=c)")look("a(?!c)")look("(?<=b)a")look("(?<!b)a")

bacad
bacad
bacad
bacad

.a.aa.aaa.a.aa.aaa.a.aa.aaa.a.aa.aaa.a.aa.aaa.a.aa.aaa

matches

sets precedence

examplealt("(ab|d)e")abcde

Use an escaped number to refer to and duplicate parentheses groups that occur
earlier in a pattern. Refer to each group by its order of appearance
string(type this)regexp(to mean this)matches(which matches this)example(the result is the same as ref("abba"))\\1\1 (etc.)

first () group, etc.

ref("(a)(b)\\2\\1")abbaab

RStudio® is a trademark of RStudio, Inc. • CC BY SA RStudio • info@rstudio.com • 844-448-1212 • rstudio.com • Learn more at stringr.tidyverse.org • Diagrams from @LVaudor ! • stringr 1.2.0 • Updated: 2017-10