r4ds/oreilly/regexps.html

1026 lines
65 KiB
HTML
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<section data-type="chapter" id="chp-regexps">
<h1><span id="sec-regular-expressions" class="quarto-section-identifier d-none d-lg-block"><span class="chapter-title">Regular expressions</span></span></h1>
<section id="introduction" data-type="sect1">
<h1>
Introduction</h1>
<p>In <a href="#chp-strings" data-type="xref">#chp-strings</a>, you learned a whole bunch of useful functions for working with strings. This chapter will focus on functions that use <strong>regular expressions</strong>, a concise and powerful language for describing patterns within strings. The term “regular expression” is a bit of a mouthful, so most people abbreviate it to “regex”<span data-type="footnote">You can pronounce it with either a hard-g (reg-x) or a soft-g (rej-x).</span> or “regexp”.</p>
<p>The chapter starts with the basics of regular expressions and the most useful stringr functions for data analysis. Well then expand your knowledge of patterns and cover seven important new topics (escaping, anchoring, character classes, shorthand classes, quantifiers, precedence, and grouping). Next, well talk about some of the other types of patterns that stringr functions can work with and the various “flags” that allow you to tweak the operation of regular expressions. Well finish with a survey of other places in the tidyverse and base R where you might use regexes.</p>
<section id="prerequisites" data-type="sect2">
<h2>
Prerequisites</h2>
<div data-type="important"><div class="callout-body d-flex">
<div class="callout-icon-container">
<i class="callout-icon"/>
</div>
</div>
<p>This chapter relies on features only found in tidyr 1.3.0, which is still in development. If you want to live on the edge, you can get the dev version with <code>devtools::install_github("tidyverse/tidyr")</code>.</p></div>
<p>In this chapter, well use regular expression functions from stringr and tidyr, both core members of the tidyverse, as well as data from the babynames package.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">library(tidyverse)
library(babynames)</pre>
</div>
<p>Through this chapter, well use a mix of very simple inline examples so you can get the basic idea, the baby names data, and three character vectors from stringr:</p>
<ul><li>
<code>fruit</code> contains the names of 80 fruits.</li>
<li>
<code>words</code> contains 980 common English words.</li>
<li>
<code>sentences</code> contains 720 short sentences.</li>
</ul></section>
</section>
<section id="sec-reg-basics" data-type="sect1">
<h1>
Pattern basics</h1>
<p>Well use <code><a href="https://stringr.tidyverse.org/reference/str_view.html">str_view()</a></code> to learn how regex patterns work. We used <code><a href="https://stringr.tidyverse.org/reference/str_view.html">str_view()</a></code> in the last chapter to better understand a string vs. its printed representation, and now well use it with its second argument, a regular expression. When this is supplied, <code><a href="https://stringr.tidyverse.org/reference/str_view.html">str_view()</a></code> will show only the elements of the string vector that match, surrounding each match with <code>&lt;&gt;</code>, and, where possible, highlighting the match in blue.</p>
<p>The simplest patterns consist of letters and numbers which match those characters exactly:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(fruit, "berry")
#&gt; [6] │ bil&lt;berry&gt;
#&gt; [7] │ black&lt;berry&gt;
#&gt; [10] │ blue&lt;berry&gt;
#&gt; [11] │ boysen&lt;berry&gt;
#&gt; [19] │ cloud&lt;berry&gt;
#&gt; [21] │ cran&lt;berry&gt;
#&gt; [29] │ elder&lt;berry&gt;
#&gt; [32] │ goji &lt;berry&gt;
#&gt; [33] │ goose&lt;berry&gt;
#&gt; [38] │ huckle&lt;berry&gt;
#&gt; ... and 4 more
str_view(fruit, "BERRY")</pre>
</div>
<p>Letters and numbers match exactly and are called <strong>literal characters</strong>. Punctuation characters like <code>.</code>, <code>+</code>, <code>*</code>, <code>[</code>, <code>]</code>, <code>?</code> have special meanings<span data-type="footnote">Youll learn how to escape these special meanings in <a href="#sec-regexp-escaping" data-type="xref">#sec-regexp-escaping</a>.</span> and are called <strong>meta-characters</strong>. For example, <code>.</code> will match any character<span data-type="footnote">Well, any character apart from <code>\n</code>.</span>, so <code>"a."</code> will match any string that contains an “a” followed by another character :</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(c("a", "ab", "ae", "bd", "ea", "eab"), "a.")
#&gt; [2] │ &lt;ab&gt;
#&gt; [3] │ &lt;ae&gt;
#&gt; [6] │ e&lt;ab&gt;</pre>
</div>
<p>Or we could find all the fruits that contain an “a”, followed by three letters, followed by an “e”:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(fruit, "a...e")
#&gt; [1] │ &lt;apple&gt;
#&gt; [7] │ bl&lt;ackbe&gt;rry
#&gt; [48] │ mand&lt;arine&gt;
#&gt; [51] │ nect&lt;arine&gt;
#&gt; [62] │ pine&lt;apple&gt;
#&gt; [64] │ pomegr&lt;anate&gt;
#&gt; [70] │ r&lt;aspbe&gt;rry
#&gt; [73] │ sal&lt;al be&gt;rry</pre>
</div>
<p><strong>Quantifiers</strong> control how many times a pattern can match:</p>
<ul><li>
<code>?</code> makes a pattern optional (i.e., it matches 0 or 1 times)</li>
<li>
<code>+</code> lets a pattern repeat (i.e., it matches at least once)</li>
<li>
<code>*</code> lets a pattern be optional or repeat (i.e., it matches any number of times, including 0).</li>
</ul><div class="cell">
<pre data-type="programlisting" data-code-language="r"># ab? matches an "a", optionally followed by a "b".
str_view(c("a", "ab", "abb"), "ab?")
#&gt; [1] │ &lt;a&gt;
#&gt; [2] │ &lt;ab&gt;
#&gt; [3] │ &lt;ab&gt;b
# ab+ matches an "a", followed by at least one "b".
str_view(c("a", "ab", "abb"), "ab+")
#&gt; [2] │ &lt;ab&gt;
#&gt; [3] │ &lt;abb&gt;
# ab* matches an "a", followed by any number of "b"s.
str_view(c("a", "ab", "abb"), "ab*")
#&gt; [1] │ &lt;a&gt;
#&gt; [2] │ &lt;ab&gt;
#&gt; [3] │ &lt;abb&gt;</pre>
</div>
<p><strong>Character classes</strong> are defined by <code>[]</code> and let you match a set of characters, e.g. <code>[abcd]</code> matches “a”, “b”, “c”, or “d”. You can also invert the match by starting with <code>^</code>: <code>[^abcd]</code> matches anything <strong>except</strong> “a”, “b”, “c”, or “d”. We can use this idea to find the words with three vowels or four consonants in a row:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(words, "[aeiou][aeiou][aeiou]")
#&gt; [79] │ b&lt;eau&gt;ty
#&gt; [565] │ obv&lt;iou&gt;s
#&gt; [644] │ prev&lt;iou&gt;s
#&gt; [670] │ q&lt;uie&gt;t
#&gt; [741] │ ser&lt;iou&gt;s
#&gt; [915] │ var&lt;iou&gt;s
str_view(words, "[^aeiou][^aeiou][^aeiou][^aeiou]")
#&gt; [45] │ a&lt;pply&gt;
#&gt; [198] │ cou&lt;ntry&gt;
#&gt; [424] │ indu&lt;stry&gt;
#&gt; [830] │ su&lt;pply&gt;
#&gt; [836] │ &lt;syst&gt;em</pre>
</div>
<p>You can combine character classes and quantifiers. For example, the following regexp looks for two vowels followed by two or more consonants:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(words, "[aeiou][aeiou][^aeiou][^aeiou]+")
#&gt; [6] │ acc&lt;ount&gt;
#&gt; [21] │ ag&lt;ainst&gt;
#&gt; [31] │ alr&lt;eady&gt;
#&gt; [34] │ alth&lt;ough&gt;
#&gt; [37] │ am&lt;ount&gt;
#&gt; [46] │ app&lt;oint&gt;
#&gt; [47] │ appr&lt;oach&gt;
#&gt; [52] │ ar&lt;ound&gt;
#&gt; [61] │ &lt;auth&gt;ority
#&gt; [79] │ be&lt;auty&gt;
#&gt; ... and 62 more</pre>
</div>
<p>(Well learn more elegant ways to express these ideas in <a href="#sec-quantifiers" data-type="xref">#sec-quantifiers</a>.)</p>
<p>You can use <strong>alternation</strong>, <code>|</code> to pick between one or more alternative patterns. For example, the following patterns look for fruits containing “apple”, “pear”, or “banana”, or a repeated vowel.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(fruit, "apple|pear|banana")
#&gt; [1] │ &lt;apple&gt;
#&gt; [4] │ &lt;banana&gt;
#&gt; [59] │ &lt;pear&gt;
#&gt; [62] │ pine&lt;apple&gt;
str_view(fruit, "aa|ee|ii|oo|uu")
#&gt; [9] │ bl&lt;oo&gt;d orange
#&gt; [33] │ g&lt;oo&gt;seberry
#&gt; [47] │ lych&lt;ee&gt;
#&gt; [66] │ purple mangost&lt;ee&gt;n</pre>
</div>
<p>Regular expressions are very compact and use a lot of punctuation characters, so they can seem overwhelming and hard to read at first. Dont worry; youll get better with practice, and simple patterns will soon become second nature. Lets kick off that process by practicing with some useful stringr functions.</p>
<section id="exercises" data-type="sect2">
<h2>
Exercises</h2>
</section>
</section>
<section id="sec-stringr-regex-funs" data-type="sect1">
<h1>
Key functions</h1>
<p>Now that youve got the basics of regular expressions under your belt, lets use them with some stringr and tidyr functions. In the following section, youll learn how to detect the presence or absence of a match, how to count the number of matches, how to replace a match with fixed text, and how to extract text using a pattern.</p>
<section id="detect-matches" data-type="sect2">
<h2>
Detect matches</h2>
<p><code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code> returns a logical vector that is <code>TRUE</code> if the pattern matches an element of the character vector and <code>FALSE</code> otherwise:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_detect(c("a", "b", "c"), "[aeiou]")
#&gt; [1] TRUE FALSE FALSE</pre>
</div>
<p>Since <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code> returns a logical vector of the same length as the initial vector, it pairs well with <code><a href="https://dplyr.tidyverse.org/reference/filter.html">filter()</a></code>. For example, this code finds all the most popular names containing a lower-case “x”:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">babynames |&gt;
filter(str_detect(name, "x")) |&gt;
count(name, wt = n, sort = TRUE)
#&gt; # A tibble: 974 × 2
#&gt; name n
#&gt; &lt;chr&gt; &lt;int&gt;
#&gt; 1 Alexander 665492
#&gt; 2 Alexis 399551
#&gt; 3 Alex 278705
#&gt; 4 Alexandra 232223
#&gt; 5 Max 148787
#&gt; 6 Alexa 123032
#&gt; # … with 968 more rows</pre>
</div>
<p>We can also use <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code> with <code><a href="https://dplyr.tidyverse.org/reference/summarise.html">summarize()</a></code> by pairing it with <code><a href="https://rdrr.io/r/base/sum.html">sum()</a></code> or <code><a href="https://rdrr.io/r/base/mean.html">mean()</a></code>: <code>sum(str_detect(x, pattern))</code> tells you the number of observations that match and <code>mean(str_detect(x, pattern))</code> tells you the proportion that match. For example, the following snippet computes and visualizes the proportion of baby names<span data-type="footnote">This gives us the proportion of <strong>names</strong> that contain an “x”; if you wanted the proportion of babies with a name containing an x, youd need to perform a weighted mean.</span> that contain “x”, broken down by year. It looks like theyve radically increased in popularity lately!</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">babynames |&gt;
group_by(year) |&gt;
summarize(prop_x = mean(str_detect(name, "x"))) |&gt;
ggplot(aes(x = year, y = prop_x)) +
geom_line()</pre>
<div class="cell-output-display">
<figure id="fig-x-names"><p><img src="regexps_files/figure-html/fig-x-names-1.png" alt="A time series showing the proportion of baby names that contain the letter x. The proportion declines gradually from 8 per 1000 in 1880 to 4 per 1000 in 1980, then increases rapidly to 16 per 1000 in 2019." width="576"/></p>
<figcaption>A time series showing the proportion of baby names that contain a lower case “x”.</figcaption>
</figure>
</div>
</div>
<p>There are two functions that are closely related to <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code>, namely <code><a href="https://stringr.tidyverse.org/reference/str_subset.html">str_subset()</a></code> which returns just the strings that contain a match and <code><a href="https://stringr.tidyverse.org/reference/str_which.html">str_which()</a></code> which returns the indexes of strings that have a match:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_subset(c("a", "b", "c"), "[aeiou]")
#&gt; [1] "a"
str_which(c("a", "b", "c"), "[aeiou]")
#&gt; [1] 1</pre>
</div>
</section>
<section id="count-matches" data-type="sect2">
<h2>
Count matches</h2>
<p>The next step up in complexity from <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code> is <code><a href="https://stringr.tidyverse.org/reference/str_count.html">str_count()</a></code>: rather than a simple true or false, it tells you how many matches there are in each string.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- c("apple", "banana", "pear")
str_count(x, "p")
#&gt; [1] 2 0 1</pre>
</div>
<p>Note that each match starts at the end of the previous match; i.e. regex matches never overlap. For example, in <code>"abababa"</code>, how many times will the pattern <code>"aba"</code> match? Regular expressions say two, not three:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_count("abababa", "aba")
#&gt; [1] 2
str_view("abababa", "aba")
#&gt; [1] │ &lt;aba&gt;b&lt;aba&gt;</pre>
</div>
<p>Its natural to use <code><a href="https://stringr.tidyverse.org/reference/str_count.html">str_count()</a></code> with <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code>. The following example uses <code><a href="https://stringr.tidyverse.org/reference/str_count.html">str_count()</a></code> with character classes to count the number of vowels and consonants in each name.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">babynames |&gt;
count(name) |&gt;
mutate(
vowels = str_count(name, "[aeiou]"),
consonants = str_count(name, "[^aeiou]")
)
#&gt; # A tibble: 97,310 × 4
#&gt; name n vowels consonants
#&gt; &lt;chr&gt; &lt;int&gt; &lt;int&gt; &lt;int&gt;
#&gt; 1 Aaban 10 2 3
#&gt; 2 Aabha 5 2 3
#&gt; 3 Aabid 2 2 3
#&gt; 4 Aabir 1 2 3
#&gt; 5 Aabriella 5 4 5
#&gt; 6 Aada 1 2 2
#&gt; # … with 97,304 more rows</pre>
</div>
<p>If you look closely, youll notice that theres something off with our calculations: “Aaban” contains three “a”s, but our summary reports only two vowels. Thats because regular expressions are case sensitive. There are three ways we could fix this:</p>
<ul><li>Add the upper case vowels to the character class: <code>str_count(name, "[aeiouAEIOU]")</code>.</li>
<li>Tell the regular expression to ignore case: <code>str_count(regex(name, ignore_case = TRUE), "[aeiou]")</code>. Well talk about more in <a href="#sec-flags" data-type="xref">#sec-flags</a>.</li>
<li>Use <code><a href="https://stringr.tidyverse.org/reference/case.html">str_to_lower()</a></code> to convert the names to lower case: <code>str_count(str_to_lower(name), "[aeiou]")</code>.</li>
</ul><p>This variety of approaches is pretty typical when working with strings — there are often multiple ways to reach your goal, either by making your pattern more complicated or by doing some preprocessing on your string. If you get stuck trying one approach, it can often be useful to switch gears and tackle the problem from a different perspective.</p>
<p>In this case, since were applying two functions to the name, I think its easier to transform it first:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">babynames |&gt;
count(name) |&gt;
mutate(
name = str_to_lower(name),
vowels = str_count(name, "[aeiou]"),
consonants = str_count(name, "[^aeiou]")
)
#&gt; # A tibble: 97,310 × 4
#&gt; name n vowels consonants
#&gt; &lt;chr&gt; &lt;int&gt; &lt;int&gt; &lt;int&gt;
#&gt; 1 aaban 10 3 2
#&gt; 2 aabha 5 3 2
#&gt; 3 aabid 2 3 2
#&gt; 4 aabir 1 3 2
#&gt; 5 aabriella 5 5 4
#&gt; 6 aada 1 3 1
#&gt; # … with 97,304 more rows</pre>
</div>
</section>
<section id="replace-values" data-type="sect2">
<h2>
Replace values</h2>
<p>As well as detecting and counting matches, we can also modify them with <code><a href="https://stringr.tidyverse.org/reference/str_replace.html">str_replace()</a></code> and <code><a href="https://stringr.tidyverse.org/reference/str_replace.html">str_replace_all()</a></code>. <code><a href="https://stringr.tidyverse.org/reference/str_replace.html">str_replace()</a></code> replaces the first match, and as the name suggests, <code><a href="https://stringr.tidyverse.org/reference/str_replace.html">str_replace_all()</a></code> replaces all matches.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- c("apple", "pear", "banana")
str_replace_all(x, "[aeiou]", "-")
#&gt; [1] "-ppl-" "p--r" "b-n-n-"</pre>
</div>
<p><code><a href="https://stringr.tidyverse.org/reference/str_remove.html">str_remove()</a></code> and <code><a href="https://stringr.tidyverse.org/reference/str_remove.html">str_remove_all()</a></code> are handy shortcuts for <code>str_replace(x, pattern, "")</code>.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- c("apple", "pear", "banana")
str_remove_all(x, "[aeiou]")
#&gt; [1] "ppl" "pr" "bnn"</pre>
</div>
<p>These functions are naturally paired with <code><a href="https://dplyr.tidyverse.org/reference/mutate.html">mutate()</a></code> when doing data cleaning, and youll often apply them repeatedly to peel off layers of inconsistent formatting.</p>
</section>
<section id="sec-extract-variables" data-type="sect2">
<h2>
Extract variables</h2>
<p>The last function well discuss uses regular expressions to extract data out of one column into one or more new columns: <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_regex()</a></code>. Its a peer of the <code>separate_wider_location()</code> and <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_delim()</a></code> functions that you learned about in <a href="#sec-string-columns" data-type="xref">#sec-string-columns</a>. These functions live in tidyr because the operates on (columns of) data frames, rather than individual vectors.</p>
<p>Lets create a simple dataset to show how it works. Here we have some data derived from <code>babynames</code> where we have the name, gender, and age of a bunch of people in a rather weird format<span data-type="footnote">We wish we could reassure you that youd never see something this weird in real life, but unfortunately over the course of your career youre likely to see much weirder!</span>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df &lt;- tribble(
~str,
"&lt;Sheryl&gt;-F_34",
"&lt;Kisha&gt;-F_45",
"&lt;Brandon&gt;-N_33",
"&lt;Sharon&gt;-F_38",
"&lt;Penny&gt;-F_58",
"&lt;Justin&gt;-M_41",
"&lt;Patricia&gt;-F_84",
)</pre>
</div>
<p>To extract this data using <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_regex()</a></code> we just need to construct a sequence of regular expressions that match each piece. If we want the contents of that piece to appear in the output, we give it a name:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">df |&gt;
separate_wider_regex(
str,
patterns = c(
"&lt;", name = "[A-Za-z]+", "&gt;-",
gender = ".", "_",
age = "[0-9]+"
)
)
#&gt; # A tibble: 7 × 3
#&gt; name gender age
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
#&gt; 1 Sheryl F 34
#&gt; 2 Kisha F 45
#&gt; 3 Brandon N 33
#&gt; 4 Sharon F 38
#&gt; 5 Penny F 58
#&gt; 6 Justin M 41
#&gt; # … with 1 more row</pre>
</div>
<p>If the match fails, you can use <code>too_short = "debug"</code> to figure out what went wrong, just like <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_delim()</a></code> and <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_position()</a></code>.</p>
</section>
<section id="exercises-1" data-type="sect2">
<h2>
Exercises</h2>
<ol type="1"><li><p>What baby name has the most vowels? What name has the highest proportion of vowels? (Hint: what is the denominator?)</p></li>
<li><p>Replace all forward slashes in a string with backslashes.</p></li>
<li><p>Implement a simple version of <code><a href="https://stringr.tidyverse.org/reference/case.html">str_to_lower()</a></code> using <code><a href="https://stringr.tidyverse.org/reference/str_replace.html">str_replace_all()</a></code>.</p></li>
<li><p>Create a regular expression that will match telephone numbers as commonly written in your country.</p></li>
</ol></section>
</section>
<section id="pattern-details" data-type="sect1">
<h1>
Pattern details</h1>
<p>Now that you understand the basics of the pattern language and how to use it with some stringr and tidyr functions, its time to dig into more of the details. First, well start with <strong>escaping</strong>, which allows you to match metacharacters that would otherwise be treated specially. Next, youll learn about <strong>anchors</strong> which allow you to match the start or end of the string. Then, youll more learn about <strong>character classes</strong> and their shortcuts which allow you to match any character from a set. Next, youll learn the final details of <strong>quantifiers</strong> which control how many times a pattern can match. Then, we have to cover the important (but complex) topic of <strong>operator precedence</strong> and parentheses. And well finish off with some details of <strong>grouping</strong> components of the pattern.</p>
<p>The terms we use here are the technical names for each component. Theyre not always the most evocative of their purpose, but its very helpful to know the correct terms if you later want to Google for more details.</p>
<section id="sec-regexp-escaping" data-type="sect2">
<h2>
Escaping</h2>
<p>In order to match a literal <code>.</code>, you need an <strong>escape</strong> which tells the regular expression to match metacharacters literally. Like strings, regexps use the backslash for escaping. So, to match a <code>.</code>, you need the regexp <code>\.</code>. Unfortunately this creates a problem. We use strings to represent regular expressions, and <code>\</code> is also used as an escape symbol in strings. So to create the regular expression <code>\.</code> we need the string <code>"\\."</code>, as the following example shows.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r"># To create the regular expression \., we need to use \\.
dot &lt;- "\\."
# But the expression itself only contains one \
str_view(dot)
#&gt; [1] │ \.
# And this tells R to look for an explicit .
str_view(c("abc", "a.c", "bef"), "a\\.c")
#&gt; [2] │ &lt;a.c&gt;</pre>
</div>
<p>In this book, well usually write regular expression without quotes, like <code>\.</code>. If we need to emphasize what youll actually type, well surround it with quotes and add extra escapes, like <code>"\\."</code>.</p>
<p>If <code>\</code> is used as an escape character in regular expressions, how do you match a literal <code>\</code>? Well, you need to escape it, creating the regular expression <code>\\</code>. To create that regular expression, you need to use a string, which also needs to escape <code>\</code>. That means to match a literal <code>\</code> you need to write <code>"\\\\"</code> — you need four backslashes to match one!</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- "a\\b"
str_view(x)
#&gt; [1] │ a\b
str_view(x, "\\\\")
#&gt; [1] │ a&lt;\&gt;b</pre>
</div>
<p>Alternatively, you might find it easier to use the raw strings you learned about in <a href="#sec-raw-strings" data-type="xref">#sec-raw-strings</a>). That lets you to avoid one layer of escaping:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(x, r"{\\}")
#&gt; [1] │ a&lt;\&gt;b</pre>
</div>
<p>If youre trying to match a literal <code>.</code>, <code>$</code>, <code>|</code>, <code>*</code>, <code>+</code>, <code>?</code>, <code>{</code>, <code>}</code>, <code>(</code>, <code>)</code>, theres an alternative to using a backslash escape: you can use a character class: <code>[.]</code>, <code>[$]</code>, <code>[|]</code>, ... all match the literal values.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(c("abc", "a.c", "a*c", "a c"), "a[.]c")
#&gt; [2] │ &lt;a.c&gt;
str_view(c("abc", "a.c", "a*c", "a c"), ".[*]c")
#&gt; [3] │ &lt;a*c&gt;</pre>
</div>
<p>The full set of metacharacters is <code>.^$\|*+?{}[]()</code>. In general, look at punctuation characters with suspicion; if your regular expression isnt matching what you think it should, check if youve used any of these characters.</p>
</section>
<section id="anchors" data-type="sect2">
<h2>
Anchors</h2>
<p>By default, regular expressions will match any part of a string. If you want to match at the start of end you need to <strong>anchor</strong> the regular expression using <code>^</code> to match the start of the string or <code>$</code> to match the end of the string:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(fruit, "^a")
#&gt; [1] │ &lt;a&gt;pple
#&gt; [2] │ &lt;a&gt;pricot
#&gt; [3] │ &lt;a&gt;vocado
str_view(fruit, "a$")
#&gt; [4] │ banan&lt;a&gt;
#&gt; [15] │ cherimoy&lt;a&gt;
#&gt; [30] │ feijo&lt;a&gt;
#&gt; [36] │ guav&lt;a&gt;
#&gt; [56] │ papay&lt;a&gt;
#&gt; [74] │ satsum&lt;a&gt;</pre>
</div>
<p>Its tempting to think that <code>$</code> should matches the start of a string, because thats how we write dollar amounts, but its not what regular expressions want.</p>
<p>To force a regular expression to only the full string, anchor it with both <code>^</code> and <code>$</code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(fruit, "apple")
#&gt; [1] │ &lt;apple&gt;
#&gt; [62] │ pine&lt;apple&gt;
str_view(fruit, "^apple$")
#&gt; [1] │ &lt;apple&gt;</pre>
</div>
<p>You can also match the boundary between words (i.e. the start or end of a word) with <code>\b</code>. This can be particularly when using RStudios find and replace tool. For example, if to find all uses of <code><a href="https://rdrr.io/r/base/sum.html">sum()</a></code>, you can search for <code>\bsum\b</code> to avoid matching <code>summarize</code>, <code>summary</code>, <code>rowsum</code> and so on:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- c("summary(x)", "summarize(df)", "rowsum(x)", "sum(x)")
str_view(x, "sum")
#&gt; [1] │ &lt;sum&gt;mary(x)
#&gt; [2] │ &lt;sum&gt;marize(df)
#&gt; [3] │ row&lt;sum&gt;(x)
#&gt; [4] │ &lt;sum&gt;(x)
str_view(x, "\\bsum\\b")
#&gt; [4] │ &lt;sum&gt;(x)</pre>
</div>
<p>When used alone, anchors will produce a zero-width match:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view("abc", c("$", "^", "\\b"))
#&gt; [1] │ abc&lt;&gt;
#&gt; [2] │ &lt;&gt;abc
#&gt; [3] │ &lt;&gt;abc&lt;&gt;</pre>
</div>
<p>This helps you understand what happens when you replace a standalone anchor:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_replace_all("abc", c("$", "^", "\\b"), "--")
#&gt; [1] "abc--" "--abc" "--abc--"</pre>
</div>
</section>
<section id="character-classes" data-type="sect2">
<h2>
Character classes</h2>
<p>A <strong>character class</strong>, or character <strong>set</strong>, allows you to match any character in a set. As we discussed above, you can construct your own sets with <code>[]</code>, where <code>[abc]</code> matches a, b, or c. There are three characters that have special meaning inside of <code>[]:</code></p>
<ul><li>
<code>-</code> defines a range, e.g. <code>[a-z]</code> matches any lower case letter and <code>[0-9]</code> matches any number.</li>
<li>
<code>^</code> takes the inverse of the set, e.g. <code>[^abc]</code> matches anything except a, b, or c.</li>
<li>
<code>\</code> escapes special characters, so <code>[\^\-\]]</code> matches <code>^</code>, <code>-</code>, or <code>]</code>.</li>
</ul><p>Here are few examples:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- "abcd ABCD 12345 -!@#%."
str_view(x, "[abc]+")
#&gt; [1] │ &lt;abc&gt;d ABCD 12345 -!@#%.
str_view(x, "[a-z]+")
#&gt; [1] │ &lt;abcd&gt; ABCD 12345 -!@#%.
str_view(x, "[^a-z0-9]+")
#&gt; [1] │ abcd&lt; ABCD &gt;12345&lt; -!@#%.&gt;
# You need an escape to match characters that are otherwise
# special inside of []
str_view("a-b-c", "[a-c]")
#&gt; [1] │ &lt;a&gt;-&lt;b&gt;-&lt;c&gt;
str_view("a-b-c", "[a\\-c]")
#&gt; [1] │ &lt;a&gt;&lt;-&gt;b&lt;-&gt;&lt;c&gt;</pre>
</div>
<p>Some character classes are used so commonly that they get their own shortcut. Youve already seen <code>.</code>, which matches any character apart from a newline. There are three other particularly useful pairs<span data-type="footnote">Remember, to create a regular expression containing <code>\d</code> or <code>\s</code>, youll need to escape the <code>\</code> for the string, so youll type <code>"\\d"</code> or <code>"\\s"</code>.</span>:</p>
<ul><li>
<code>\d</code> matches any digit;<br/><code>\D</code> matches anything that isnt a digit.</li>
<li>
<code>\s</code> matches any whitespace (e.g. space, tab, newline);<br/><code>\S</code> matches anything that isnt whitespace.</li>
<li>
<code>\w</code> matches any “word” character, i.e. letters and numbers;<br/><code>\W</code> matches any “non-word” character.</li>
</ul><p>The following code demonstrates the six shortcuts with a selection of letters, numbers, and punctuation characters.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- "abcd ABCD 12345 -!@#%."
str_view(x, "\\d+")
#&gt; [1] │ abcd ABCD &lt;12345&gt; -!@#%.
str_view(x, "\\D+")
#&gt; [1] │ &lt;abcd ABCD &gt;12345&lt; -!@#%.&gt;
str_view(x, "\\w+")
#&gt; [1] │ &lt;abcd&gt; &lt;ABCD&gt; &lt;12345&gt; -!@#%.
str_view(x, "\\W+")
#&gt; [1] │ abcd&lt; &gt;ABCD&lt; &gt;12345&lt; -!@#%.&gt;
str_view(x, "\\s+")
#&gt; [1] │ abcd&lt; &gt;ABCD&lt; &gt;12345&lt; &gt;-!@#%.
str_view(x, "\\S+")
#&gt; [1] │ &lt;abcd&gt; &lt;ABCD&gt; &lt;12345&gt; &lt;-!@#%.&gt;</pre>
</div>
</section>
<section id="sec-quantifiers" data-type="sect2">
<h2>
Quantifiers</h2>
<p><strong>Quantifiers</strong> control how many times a pattern matches. In <a href="#sec-reg-basics" data-type="xref">#sec-reg-basics</a> you learned about <code>?</code> (0 or 1 matches), <code>+</code> (1 or more matches), and <code>*</code> (0 or more matches). For example, <code>colou?r</code> will match American or British spelling, <code>\d+</code> will match one or more digits, and <code>\s?</code> will optionally match a single item of whitespace. You can also specify the number of matches precisely with <code><a href="https://rdrr.io/r/base/Paren.html">{}</a></code>:</p>
<ul><li>
<code>{n}</code> matches exactly n times.</li>
<li>
<code>{n,}</code> matches at least n times.</li>
<li>
<code>{n,m}</code> matches between n and m times.</li>
</ul><p>The following code shows how this works for a few simple examples:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- "-- -x- -xx- -xxx- -xxxx- -xxxxx-"
str_view(x, "-x?-") # [0, 1]
#&gt; [1] │ &lt;--&gt; &lt;-x-&gt; -xx- -xxx- -xxxx- -xxxxx-
str_view(x, "-x+-") # [1, Inf)
#&gt; [1] │ -- &lt;-x-&gt; &lt;-xx-&gt; &lt;-xxx-&gt; &lt;-xxxx-&gt; &lt;-xxxxx-&gt;
str_view(x, "-x*-") # [0, Inf)
#&gt; [1] │ &lt;--&gt; &lt;-x-&gt; &lt;-xx-&gt; &lt;-xxx-&gt; &lt;-xxxx-&gt; &lt;-xxxxx-&gt;
str_view(x, "-x{2}-") # [2. 2]
#&gt; [1] │ -- -x- &lt;-xx-&gt; -xxx- -xxxx- -xxxxx-
str_view(x, "-x{2,}-") # [2, Inf)
#&gt; [1] │ -- -x- &lt;-xx-&gt; &lt;-xxx-&gt; &lt;-xxxx-&gt; &lt;-xxxxx-&gt;
str_view(x, "-x{2,3}-") # [2, 3]
#&gt; [1] │ -- -x- &lt;-xx-&gt; &lt;-xxx-&gt; -xxxx- -xxxxx-</pre>
</div>
</section>
<section id="operator-precedence-and-parentheses" data-type="sect2">
<h2>
Operator precedence and parentheses</h2>
<p>What does <code>ab+</code> match? Does it match “a” followed by one or more “b”s, or does it match “ab” repeated any number of times? What does <code>^a|b$</code> match? Does it match the complete string a or the complete string b, or does it match a string starting with a or a string starting with “b”?</p>
<p>The answer to these questions is determined by operator precedence, similar to the PEMDAS or BEDMAS rules you might have learned in school. You know that <code>a + b * c</code> is equivalent to <code>a + (b * c)</code> not <code>(a + b) * c</code> because <code>*</code> has higher precedence and <code>+</code> has lower precedence: you compute <code>*</code> before <code>+</code>.</p>
<p>Similarly, regular expressions have their own precedence rules: quantifiers have high precedence and alternation has low precedence which means that <code>ab+</code> is equivalent to <code>a(b+)</code>, and <code>^a|b$</code> is equivalent to <code>(^a)|(b$)</code>. Just like with algebra, you can use parentheses to override the usual order. But unlike algebra youre unlikely to remember the precedence rules for regexes, so feel free to use parentheses liberally.</p>
</section>
<section id="grouping-and-capturing" data-type="sect2">
<h2>
Grouping and capturing</h2>
<p>As well overriding operator precedence, parentheses have another important effect: they create <strong>capturing groups</strong> that allow you to use sub-components of the match.</p>
<p>The first way to use a capturing group is to refer back to it within a match with <strong>back reference</strong>: <code>\1</code> refers to the match contained in the first parenthesis, <code>\2</code> in the second parenthesis, and so on. For example, the following pattern finds all fruits that have a repeated pair of letters:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(fruit, "(..)\\1")
#&gt; [4] │ b&lt;anan&gt;a
#&gt; [20] │ &lt;coco&gt;nut
#&gt; [22] │ &lt;cucu&gt;mber
#&gt; [41] │ &lt;juju&gt;be
#&gt; [56] │ &lt;papa&gt;ya
#&gt; [73] │ s&lt;alal&gt; berry</pre>
</div>
<p>And this one finds all words that start and end with the same pair of letters:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(words, "^(..).*\\1$")
#&gt; [152] │ &lt;church&gt;
#&gt; [217] │ &lt;decide&gt;
#&gt; [617] │ &lt;photograph&gt;
#&gt; [699] │ &lt;require&gt;
#&gt; [739] │ &lt;sense&gt;</pre>
</div>
<p>You can also use back references in <code><a href="https://stringr.tidyverse.org/reference/str_replace.html">str_replace()</a></code>. For example, this code switches the order of the second and third words in <code>sentences</code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">sentences |&gt;
str_replace("(\\w+) (\\w+) (\\w+)", "\\1 \\3 \\2") |&gt;
str_view()
#&gt; [1] │ The canoe birch slid on the smooth planks.
#&gt; [2] │ Glue sheet the to the dark blue background.
#&gt; [3] │ It's to easy tell the depth of a well.
#&gt; [4] │ These a days chicken leg is a rare dish.
#&gt; [5] │ Rice often is served in round bowls.
#&gt; [6] │ The of juice lemons makes fine punch.
#&gt; [7] │ The was box thrown beside the parked truck.
#&gt; [8] │ The were hogs fed chopped corn and garbage.
#&gt; [9] │ Four of hours steady work faced us.
#&gt; [10] │ A size large in stockings is hard to sell.
#&gt; ... and 710 more</pre>
</div>
<p>If you want extract the matches for each group you can use <code><a href="https://stringr.tidyverse.org/reference/str_match.html">str_match()</a></code>. But <code><a href="https://stringr.tidyverse.org/reference/str_match.html">str_match()</a></code> returns a matrix, so its not particularly easy to work with<span data-type="footnote">Mostly because we never discuss matrices in this book!</span>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">sentences |&gt;
str_match("the (\\w+) (\\w+)") |&gt;
head()
#&gt; [,1] [,2] [,3]
#&gt; [1,] "the smooth planks" "smooth" "planks"
#&gt; [2,] "the sheet to" "sheet" "to"
#&gt; [3,] "the depth of" "depth" "of"
#&gt; [4,] NA NA NA
#&gt; [5,] NA NA NA
#&gt; [6,] NA NA NA</pre>
</div>
<p>You could convert to a tibble and name the columns:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">sentences |&gt;
str_match("the (\\w+) (\\w+)") |&gt;
as_tibble(.name_repair = "minimal") |&gt;
set_names("match", "word1", "word2")
#&gt; # A tibble: 720 × 3
#&gt; match word1 word2
#&gt; &lt;chr&gt; &lt;chr&gt; &lt;chr&gt;
#&gt; 1 the smooth planks smooth planks
#&gt; 2 the sheet to sheet to
#&gt; 3 the depth of depth of
#&gt; 4 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt;
#&gt; 5 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt;
#&gt; 6 &lt;NA&gt; &lt;NA&gt; &lt;NA&gt;
#&gt; # … with 714 more rows</pre>
</div>
<p>But then youve basically recreated your own version of <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_regex()</a></code>. Indeed, behind the scenes, <code><a href="https://tidyr.tidyverse.org/reference/separate_wider_delim.html">separate_wider_regex()</a></code> converts your vector of patterns to a single regex that uses grouping to capture the named components.</p>
<p>Occasionally, youll want to use parentheses without creating matching groups. You can create a non-capturing group with <code>(?:)</code>.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- c("a gray cat", "a grey dog")
str_match(x, "gr(e|a)y")
#&gt; [,1] [,2]
#&gt; [1,] "gray" "a"
#&gt; [2,] "grey" "e"
str_match(x, "gr(?:e|a)y")
#&gt; [,1]
#&gt; [1,] "gray"
#&gt; [2,] "grey"</pre>
</div>
</section>
<section id="exercises-2" data-type="sect2">
<h2>
Exercises</h2>
<ol type="1"><li><p>How would you match the literal string <code>"'\</code>? How about <code>"$^$"</code>?</p></li>
<li><p>Explain why each of these patterns dont match a <code>\</code>: <code>"\"</code>, <code>"\\"</code>, <code>"\\\"</code>.</p></li>
<li>
<p>Given the corpus of common words in <code><a href="https://stringr.tidyverse.org/reference/stringr-data.html">stringr::words</a></code>, create regular expressions that find all words that:</p>
<ol type="a"><li>Start with “y”.</li>
<li>Dont start with “y”.</li>
<li>End with “x”.</li>
<li>Are exactly three letters long. (Dont cheat by using <code><a href="https://stringr.tidyverse.org/reference/str_length.html">str_length()</a></code>!)</li>
<li>Have seven letters or more.</li>
<li>Contain a vowel-consonant pair.</li>
<li>Contain at least two vowel-consonant pairs in a row.</li>
<li>Only consist of repeated vowel-consonant pairs.</li>
</ol></li>
<li><p>Create 11 regular expressions that match the British or American spellings for each of the following words: grey/gray, modelling/modeling, summarize/summarize, aluminium/aluminum, defence/defense, analog/analogue, center/centre, sceptic/skeptic, aeroplane/airplane, arse/ass, doughnut/donut. Try and make the shortest possible regex!</p></li>
<li><p>Switch the first and last letters in <code>words</code>. Which of those strings are still <code>words</code>?</p></li>
<li>
<p>Describe in words what these regular expressions match: (read carefully to see if each entry is a regular expression or a string that defines a regular expression.)</p>
<ol type="a"><li><code>^.*$</code></li>
<li><code>"\\{.+\\}"</code></li>
<li><code>\d{4}-\d{2}-\d{2}</code></li>
<li><code>"\\\\{4}"</code></li>
<li><code>\..\..\..</code></li>
<li><code>(.)\1\1</code></li>
<li><code>"(..)\\1"</code></li>
</ol></li>
<li><p>Solve the beginner regexp crosswords at <a href="https://regexcrossword.com/challenges/beginner" class="uri">https://regexcrossword.com/challenges/beginner</a>.</p></li>
</ol></section>
</section>
<section id="pattern-control" data-type="sect1">
<h1>
Pattern control</h1>
<p>Its possible to exercise extra control over the details of the match by using a pattern object instead of just a string. This allows you control the so called regex flags and match various types of fixed strings, as described below.</p>
<section id="sec-flags" data-type="sect2">
<h2>
Regex flags</h2>
<p>There are a number of settings that can use to control the details of the regexp. These settings are often called <strong>flags</strong> in other programming languages. In stringr, you can use these by wrapping the pattern in a call to <code><a href="https://stringr.tidyverse.org/reference/modifiers.html">regex()</a></code>. The most useful flag is probably <code>ignore_case = TRUE</code> because it allows characters to match either their uppercase or lowercase forms:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">bananas &lt;- c("banana", "Banana", "BANANA")
str_view(bananas, "banana")
#&gt; [1] │ &lt;banana&gt;
str_view(bananas, regex("banana", ignore_case = TRUE))
#&gt; [1] │ &lt;banana&gt;
#&gt; [2] │ &lt;Banana&gt;
#&gt; [3] │ &lt;BANANA&gt;</pre>
</div>
<p>If youre doing a lot of work with multiline strings (i.e. strings that contain <code>\n</code>), <code>dotall</code>and <code>multiline</code> may also be useful:</p>
<ul><li>
<p><code>dotall = TRUE</code> lets <code>.</code> match everything, including <code>\n</code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- "Line 1\nLine 2\nLine 3"
str_view(x, ".Line")
str_view(x, regex(".Line", dotall = TRUE))
#&gt; [1] │ Line 1&lt;
#&gt; │ Line&gt; 2&lt;
#&gt; │ Line&gt; 3</pre>
</div>
</li>
<li>
<p><code>multiline = TRUE</code> makes <code>^</code> and <code>$</code> match the start and end of each line rather than the start and end of the complete string:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">x &lt;- "Line 1\nLine 2\nLine 3"
str_view(x, "^Line")
#&gt; [1] │ &lt;Line&gt; 1
#&gt; │ Line 2
#&gt; │ Line 3
str_view(x, regex("^Line", multiline = TRUE))
#&gt; [1] │ &lt;Line&gt; 1
#&gt;&lt;Line&gt; 2
#&gt;&lt;Line&gt; 3</pre>
</div>
</li>
</ul><p>Finally, if youre writing a complicated regular expression and youre worried you might not understand it in the future, you might try <code>comments = TRUE</code>. It tweaks the pattern language to ignore spaces and new lines, as well as everything after <code>#</code>. This allows you to use comments and whitespace to make complex regular expressions more understandable<span data-type="footnote"><code>comments = TRUE</code> is particularly effective in combination with a raw string, as we use here.</span>, as in the following example:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">phone &lt;- regex(
r"(
\(? # optional opening parens
(\d{3}) # area code
[)\ -]? # optional closing parens, space, or dash
(\d{3}) # another three numbers
[\ -]? # optional space or dash
(\d{3}) # three more numbers
)",
comments = TRUE
)
str_match("514-791-8141", phone)
#&gt; [,1] [,2] [,3] [,4]
#&gt; [1,] "514-791-814" "514" "791" "814"</pre>
</div>
<p>If youre using comments and want to match a space, newline, or <code>#</code>, youll need to escape it:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view("x x #", regex(r"(x #)", comments = TRUE))
#&gt; [1] │ &lt;x&gt; &lt;x&gt; #
str_view("x x #", regex(r"(x\ \#)", comments = TRUE))
#&gt; [1] │ x &lt;x #&gt;</pre>
</div>
</section>
<section id="fixed-matches" data-type="sect2">
<h2>
Fixed matches</h2>
<p>You can opt-out of the regular expression rules by using <code><a href="https://stringr.tidyverse.org/reference/modifiers.html">fixed()</a></code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(c("", "a", "."), fixed("."))
#&gt; [3] │ &lt;.&gt;</pre>
</div>
<p><code><a href="https://stringr.tidyverse.org/reference/modifiers.html">fixed()</a></code> also gives you the ability to ignore case:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view("x X", "X")
#&gt; [1] │ x &lt;X&gt;
str_view("x X", fixed("X", ignore_case = TRUE))
#&gt; [1] │ &lt;x&gt; &lt;X&gt;</pre>
</div>
<p>If youre working with non-English text, you will probably want <code><a href="https://stringr.tidyverse.org/reference/modifiers.html">coll()</a></code> instead of <code><a href="https://stringr.tidyverse.org/reference/modifiers.html">fixed()</a></code>, as it implements the full rules for capitalization as used by the <code>locale</code> you specify. See <a href="#sec-other-languages" data-type="xref">#sec-other-languages</a> for more details on locales.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view("i İ ı I", fixed("İ", ignore_case = TRUE))
#&gt; [1] │ i &lt;İ&gt; ı I
str_view("i İ ı I", coll("İ", ignore_case = TRUE, locale = "tr"))
#&gt; [1] │ &lt;i&gt; &lt;İ&gt; ı I</pre>
</div>
</section>
</section>
<section id="practice" data-type="sect1">
<h1>
Practice</h1>
<p>To put these ideas into practice well solve a few semi-authentic problems next. Well discuss three general techniques:</p>
<ol type="1"><li>checking you work by creating simple positive and negative controls</li>
<li>combining regular expressions with Boolean algebra</li>
<li>creating complex patterns using string manipulation</li>
</ol>
<section id="check-your-work" data-type="sect2">
<h2>
Check your work</h2>
<p>First, lets find all sentences that start with “The”. Using the <code>^</code> anchor alone is not enough:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(sentences, "^The")
#&gt; [1] │ &lt;The&gt; birch canoe slid on the smooth planks.
#&gt; [4] │ &lt;The&gt;se days a chicken leg is a rare dish.
#&gt; [6] │ &lt;The&gt; juice of lemons makes fine punch.
#&gt; [7] │ &lt;The&gt; box was thrown beside the parked truck.
#&gt; [8] │ &lt;The&gt; hogs were fed chopped corn and garbage.
#&gt; [11] │ &lt;The&gt; boy was there when the sun rose.
#&gt; [13] │ &lt;The&gt; source of the huge river is the clear spring.
#&gt; [18] │ &lt;The&gt; soft cushion broke the man's fall.
#&gt; [19] │ &lt;The&gt; salt breeze came across from the sea.
#&gt; [20] │ &lt;The&gt; girl at the booth sold fifty bonds.
#&gt; ... and 267 more</pre>
</div>
<p>Because that pattern also matches sentences starting with words like <code>They</code> or <code>These</code>. We need to make sure that the “e” is the last letter in the word, which we can do by adding adding a word boundary:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(sentences, "^The\\b")
#&gt; [1] │ &lt;The&gt; birch canoe slid on the smooth planks.
#&gt; [6] │ &lt;The&gt; juice of lemons makes fine punch.
#&gt; [7] │ &lt;The&gt; box was thrown beside the parked truck.
#&gt; [8] │ &lt;The&gt; hogs were fed chopped corn and garbage.
#&gt; [11] │ &lt;The&gt; boy was there when the sun rose.
#&gt; [13] │ &lt;The&gt; source of the huge river is the clear spring.
#&gt; [18] │ &lt;The&gt; soft cushion broke the man's fall.
#&gt; [19] │ &lt;The&gt; salt breeze came across from the sea.
#&gt; [20] │ &lt;The&gt; girl at the booth sold fifty bonds.
#&gt; [21] │ &lt;The&gt; small pup gnawed a hole in the sock.
#&gt; ... and 246 more</pre>
</div>
<p>What about finding all sentences that begin with a pronoun?</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(sentences, "^She|He|It|They\\b")
#&gt; [3] │ &lt;It&gt;'s easy to tell the depth of a well.
#&gt; [15] │ &lt;He&gt;lp the woman get back to her feet.
#&gt; [27] │ &lt;He&gt;r purse was full of useless trash.
#&gt; [29] │ &lt;It&gt; snowed, rained, and hailed the same morning.
#&gt; [63] │ &lt;He&gt; ran half way to the hardware store.
#&gt; [90] │ &lt;He&gt; lay prone and hardly moved a limb.
#&gt; [116] │ &lt;He&gt; ordered peach pie with ice cream.
#&gt; [118] │ &lt;He&gt;mp is a weed found in parts of the tropics.
#&gt; [127] │ &lt;It&gt; caught its hind paw in a rusty trap.
#&gt; [132] │ &lt;He&gt; said the same phrase thirty times.
#&gt; ... and 53 more</pre>
</div>
<p>A quick inspection of the results shows that were getting some spurious matches. Thats because weve forgotten to use parentheses:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(sentences, "^(She|He|It|They)\\b")
#&gt; [3] │ &lt;It&gt;'s easy to tell the depth of a well.
#&gt; [29] │ &lt;It&gt; snowed, rained, and hailed the same morning.
#&gt; [63] │ &lt;He&gt; ran half way to the hardware store.
#&gt; [90] │ &lt;He&gt; lay prone and hardly moved a limb.
#&gt; [116] │ &lt;He&gt; ordered peach pie with ice cream.
#&gt; [127] │ &lt;It&gt; caught its hind paw in a rusty trap.
#&gt; [132] │ &lt;He&gt; said the same phrase thirty times.
#&gt; [153] │ &lt;He&gt; broke a new shoelace that day.
#&gt; [159] │ &lt;She&gt; sewed the torn coat quite neatly.
#&gt; [168] │ &lt;He&gt; knew the skill of the great young actress.
#&gt; ... and 47 more</pre>
</div>
<p>You might wonder how you might spot such a mistake if it didnt occur in the first few matches. A good technique is to create a few positive and negative matches and use them to test that your pattern works as expected:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">pos &lt;- c("He is a boy", "She had a good time")
neg &lt;- c("Shells come from the sea", "Hadley said 'It's a great day'")
pattern &lt;- "^(She|He|It|They)\\b"
str_detect(pos, pattern)
#&gt; [1] TRUE TRUE
str_detect(neg, pattern)
#&gt; [1] FALSE FALSE</pre>
</div>
<p>Its typically much easier to come up with good positive examples than negative examples, because it takes a while before youre good enough with regular expressions to predict where your weaknesses are. Nevertheless, theyre still useful: as you work on the problem you can slowly accumulate a collection of your mistakes, ensuring that you never make the same mistake twice.</p>
</section>
<section id="sec-boolean-operations" data-type="sect2">
<h2>
Boolean operations</h2>
<p>Imagine we want to find words that only contain consonants. One technique is to create a character class that contains all letters except for the vowels (<code>[^aeiou]</code>), then allow that to match any number of letters (<code>[^aeiou]+</code>), then force it to match the whole string by anchoring to the beginning and the end (<code>^[^aeiou]+$</code>):</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(words, "^[^aeiou]+$")
#&gt; [123] │ &lt;by&gt;
#&gt; [249] │ &lt;dry&gt;
#&gt; [328] │ &lt;fly&gt;
#&gt; [538] │ &lt;mrs&gt;
#&gt; [895] │ &lt;try&gt;
#&gt; [952] │ &lt;why&gt;</pre>
</div>
<p>But you can make this problem a bit easier by flipping the problem around. Instead of looking for words that contain only consonants, we could look for words that dont contain any vowels:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(words[!str_detect(words, "[aeiou]")])
#&gt; [1] │ by
#&gt; [2] │ dry
#&gt; [3] │ fly
#&gt; [4] │ mrs
#&gt; [5] │ try
#&gt; [6] │ why</pre>
</div>
<p>This is a useful technique whenever youre dealing with logical combinations, particularly those involving “and” or “not”. For example, imagine if you want to find all words that contain “a” and “b”. Theres no “and” operator built in to regular expressions so we have to tackle it by looking for all words that contain an “a” followed by a “b”, or a “b” followed by an “a”:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(words, "a.*b|b.*a")
#&gt; [2] │ &lt;ab&gt;le
#&gt; [3] │ &lt;ab&gt;out
#&gt; [4] │ &lt;ab&gt;solute
#&gt; [62] │ &lt;availab&gt;le
#&gt; [66] │ &lt;ba&gt;by
#&gt; [67] │ &lt;ba&gt;ck
#&gt; [68] │ &lt;ba&gt;d
#&gt; [69] │ &lt;ba&gt;g
#&gt; [70] │ &lt;bala&gt;nce
#&gt; [71] │ &lt;ba&gt;ll
#&gt; ... and 20 more</pre>
</div>
<p>Its simpler to combine the results of two calls to <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">words[str_detect(words, "a") &amp; str_detect(words, "b")]
#&gt; [1] "able" "about" "absolute" "available" "baby" "back"
#&gt; [7] "bad" "bag" "balance" "ball" "bank" "bar"
#&gt; [13] "base" "basis" "bear" "beat" "beauty" "because"
#&gt; [19] "black" "board" "boat" "break" "brilliant" "britain"
#&gt; [25] "debate" "husband" "labour" "maybe" "probable" "table"</pre>
</div>
<p>What if we wanted to see if there was a word that contains all vowels? If we did it with patterns wed need to generate 5! (120) different patterns:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">words[str_detect(words, "a.*e.*i.*o.*u")]
# ...
words[str_detect(words, "u.*o.*i.*e.*a")]</pre>
</div>
<p>Its much simpler to combine five calls to <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">words[
str_detect(words, "a") &amp;
str_detect(words, "e") &amp;
str_detect(words, "i") &amp;
str_detect(words, "o") &amp;
str_detect(words, "u")
]
#&gt; character(0)</pre>
</div>
<p>In general, if you get stuck trying to create a single regexp that solves your problem, take a step back and think if you could break the problem down into smaller pieces, solving each challenge before moving onto the next one.</p>
</section>
<section id="creating-a-pattern-with-code" data-type="sect2">
<h2>
Creating a pattern with code</h2>
<p>What if we wanted to find all <code>sentences</code> that mention a color? The basic idea is simple: we just combine alternation with word boundaries.</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(sentences, "\\b(red|green|blue)\\b")
#&gt; [2] │ Glue the sheet to the dark &lt;blue&gt; background.
#&gt; [26] │ Two &lt;blue&gt; fish swam in the tank.
#&gt; [92] │ A wisp of cloud hung in the &lt;blue&gt; air.
#&gt; [148] │ The spot on the blotter was made by &lt;green&gt; ink.
#&gt; [160] │ The sofa cushion is &lt;red&gt; and of light weight.
#&gt; [174] │ The sky that morning was clear and bright &lt;blue&gt;.
#&gt; [204] │ A &lt;blue&gt; crane is a tall wading bird.
#&gt; [217] │ It is hard to erase &lt;blue&gt; or &lt;red&gt; ink.
#&gt; [224] │ The lamp shone with a steady &lt;green&gt; flame.
#&gt; [247] │ The box is held by a bright &lt;red&gt; snapper.
#&gt; ... and 16 more</pre>
</div>
<p>But as the number of colors grows, it would quickly get tedious to construct this pattern by hand. Wouldnt it be nice if we could store the colors in a vector?</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">rgb &lt;- c("red", "green", "blue")</pre>
</div>
<p>Well, we can! Wed just need to create the pattern from the vector using <code><a href="https://stringr.tidyverse.org/reference/str_c.html">str_c()</a></code> and <code><a href="https://stringr.tidyverse.org/reference/str_flatten.html">str_flatten()</a></code>:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_c("\\b(", str_flatten(rgb, "|"), ")\\b")
#&gt; [1] "\\b(red|green|blue)\\b"</pre>
</div>
<p>We could make this pattern more comprehensive if we had a good list of colors. One place we could start from is the list of built-in colors that R can use for plots:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">str_view(colors())
#&gt; [1] │ white
#&gt; [2] │ aliceblue
#&gt; [3] │ antiquewhite
#&gt; [4] │ antiquewhite1
#&gt; [5] │ antiquewhite2
#&gt; [6] │ antiquewhite3
#&gt; [7] │ antiquewhite4
#&gt; [8] │ aquamarine
#&gt; [9] │ aquamarine1
#&gt; [10] │ aquamarine2
#&gt; ... and 647 more</pre>
</div>
<p>But lets first eliminate the numbered variants:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">cols &lt;- colors()
cols &lt;- cols[!str_detect(cols, "\\d")]
str_view(cols)
#&gt; [1] │ white
#&gt; [2] │ aliceblue
#&gt; [3] │ antiquewhite
#&gt; [4] │ aquamarine
#&gt; [5] │ azure
#&gt; [6] │ beige
#&gt; [7] │ bisque
#&gt; [8] │ black
#&gt; [9] │ blanchedalmond
#&gt; [10] │ blue
#&gt; ... and 133 more</pre>
</div>
<p>Then we can turn this into one giant pattern. We wont show the pattern here because its huge, but you can see it working:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">pattern &lt;- str_c("\\b(", str_flatten(cols, "|"), ")\\b")
str_view(sentences, pattern)
#&gt; [2] │ Glue the sheet to the dark &lt;blue&gt; background.
#&gt; [12] │ A rod is used to catch &lt;pink&gt; &lt;salmon&gt;.
#&gt; [26] │ Two &lt;blue&gt; fish swam in the tank.
#&gt; [66] │ Cars and busses stalled in &lt;snow&gt; drifts.
#&gt; [92] │ A wisp of cloud hung in the &lt;blue&gt; air.
#&gt; [112] │ Leaves turn &lt;brown&gt; and &lt;yellow&gt; in the fall.
#&gt; [148] │ The spot on the blotter was made by &lt;green&gt; ink.
#&gt; [149] │ Mud was spattered on the front of his &lt;white&gt; shirt.
#&gt; [160] │ The sofa cushion is &lt;red&gt; and of light weight.
#&gt; [167] │ The office paint was a dull, sad &lt;tan&gt;.
#&gt; ... and 53 more</pre>
</div>
<p>In this example, <code>cols</code> only contains numbers and letters so you dont need to worry about metacharacters. But in general, whenever you create create patterns from existing strings its wise to run them through <code><a href="https://stringr.tidyverse.org/reference/str_escape.html">str_escape()</a></code> to ensure they match literally.</p>
</section>
<section id="exercises-3" data-type="sect2">
<h2>
Exercises</h2>
<ol type="1"><li>
<p>For each of the following challenges, try solving it by using both a single regular expression, and a combination of multiple <code><a href="https://stringr.tidyverse.org/reference/str_detect.html">str_detect()</a></code> calls.</p>
<ol type="a"><li>Find all <code>words</code> that start or end with <code>x</code>.</li>
<li>Find all <code>words</code> that start with a vowel and end with a consonant.</li>
<li>Are there any <code>words</code> that contain at least one of each different vowel?</li>
</ol></li>
<li><p>Construct patterns to find evidence for and against the rule “i before e except after c”?</p></li>
<li><p><code><a href="https://rdrr.io/r/grDevices/colors.html">colors()</a></code> contains a number of modifiers like “lightgray” and “darkblue”. How could you automatically identify these modifiers? (Think about how you might detect and then removed the colors that are modified).</p></li>
<li><p>Create a regular expression that finds any base R dataset. You can get a list of these datasets via a special use of the <code><a href="https://rdrr.io/r/utils/data.html">data()</a></code> function: <code>data(package = "datasets")$results[, "Item"]</code>. Note that a number of old datasets are individual vectors; these contain the name of the grouping “data frame” in parentheses, so youll need to strip those off.</p></li>
</ol></section>
</section>
<section id="regular-expressions-in-other-places" data-type="sect1">
<h1>
Regular expressions in other places</h1>
<p>Just like in the stringr and tidyr functions, there are many other places in R where you can use regular expressions. The following sections describe some other useful functions in the wider tidyverse and base R.</p>
<section id="tidyverse" data-type="sect2">
<h2>
tidyverse</h2>
<p>There are three other particularly useful places where you might want to use a regular expressions</p>
<ul><li><p><code>matches(pattern)</code> will select all variables whose name matches the supplied pattern. Its a “tidyselect” function that you can use anywhere in any tidyverse function that selects variables (e.g. <code><a href="https://dplyr.tidyverse.org/reference/select.html">select()</a></code>, <code><a href="https://dplyr.tidyverse.org/reference/rename.html">rename_with()</a></code> and <code><a href="https://dplyr.tidyverse.org/reference/across.html">across()</a></code>).</p></li>
<li><p><code>pivot_longer()'s</code> <code>names_pattern</code> argument takes a vector of regular expressions, just like <code>separate_with_regex()</code>. Its useful when extracting data out of variable names with a complex structure</p></li>
<li><p>The <code>delim</code> argument in <code>separate_delim_longer()</code> and <code>separate_delim_wider()</code> usually matches a fixed string, but you can use <code><a href="https://stringr.tidyverse.org/reference/modifiers.html">regex()</a></code> to make it match a pattern. This is useful, for example, if you want to match a comma that is optionally followed by a space, i.e. <code>regex(", ?")</code>.</p></li>
</ul></section>
<section id="base-r" data-type="sect2">
<h2>
Base R</h2>
<p><code>apropos(pattern)</code> searches all objects available from the global environment that match the given pattern. This is useful if you cant quite remember the name of a function:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">apropos("replace")
#&gt; [1] "%+replace%" "replace" "replace_na"
#&gt; [4] "setReplaceMethod" "str_replace" "str_replace_all"
#&gt; [7] "str_replace_na" "theme_replace"</pre>
</div>
<p><code>list.files(path, pattern)</code> lists all files in <code>path</code> that match a regular expression <code>pattern</code>. For example, you can find all the R Markdown files in the current directory with:</p>
<div class="cell">
<pre data-type="programlisting" data-code-language="r">head(list.files(pattern = "\\.Rmd$"))
#&gt; character(0)</pre>
</div>
<p>Its worth noting that the pattern language used by base R is very slightly different to that used by stringr. Thats because stringr is built on top of the <a href="https://stringi.gagolewski.com">stringi package</a>, which is in turn built on top of the <a href="https://unicode-org.github.io/icu/userguide/strings/regexp.html">ICU engine</a>, whereas base R functions use either the <a href="https://github.com/laurikari/tre">TRE engine</a> or the <a href="https://www.pcre.org">PCRE engine</a>, depending on whether or not youve set <code>perl = TRUE</code>. Fortunately, the basics of regular expressions are so well established that youll encounter few variations when working with the patterns youll learn in this book. You only need to be aware of the difference when you start to rely on advanced features like complex Unicode character ranges or special features that use the <code>(?…)</code> syntax.</p>
</section>
</section>
<section id="summary" data-type="sect1">
<h1>
Summary</h1>
<p>With every punctuation character potentially overloaded with meaning, regular expressions are one of the most compact languages out there. Theyre definitely confusing at first but as you train your eyes to read them and your brain to understand them, you unlock a powerful skill that you can use in R and in many other places.</p>
<p>In this chapter, youve started your journey to become a regular expression master by learning the most useful stringr functions and the most important components of the regular expression language. And there are plenty of resources to learn more.</p>
<p>A good place to start is <code><a href="https://stringr.tidyverse.org/articles/regular-expressions.html">vignette("regular-expressions", package = "stringr")</a></code>: it documents the full set of syntax supported by stringr. Another useful reference is <a href="https://www.regular-expressions.info/tutorial.html">https://www.regular-expressions.info/</a>. Its not R specific, but you can use it to learn about the most advanced features of regexes and how they work under the hood.</p>
<p>Its also good to know that stringr is implemented on top of the stringi package by Marek Gagolewsk. If youre struggling to find a function that does what you need in stringr, dont be afraid to look in stringi. Youll find stringi very easy to pick up because it follows many of the the same conventions as stringr.</p>
<p>In the next chapter, well talk about a data structure closely related to strings: factors. Factors are used to represent categorical data in R, i.e. data with a fixed and known set of possible values identified by a vector of strings.</p>
</section>
</section>