r4ds/regexps.qmd

811 lines
32 KiB
Plaintext
Raw Normal View History

# Regular expressions {#sec-regular-expressions}
2021-04-21 21:43:19 +08:00
```{r}
#| results: "asis"
#| echo: false
source("_common.R")
2021-05-04 21:10:39 +08:00
status("restructuring")
```
2021-04-22 01:30:25 +08:00
## Introduction
2022-10-05 06:34:27 +08:00
In @sec-strings, you learned a whole bunch of useful functions for working with strings.
In this this chapter we'll learn even more, but these functions all use regular expressions.
Regular expressions are a powerful language for describing patterns within strings.
The term "regular expression" is a bit of a mouthful, so most people abbreviate to "regex"[^regexps-1] or "regexp".
2022-01-04 05:25:03 +08:00
2022-10-05 06:34:27 +08:00
[^regexps-1]: With a hard g, sounding like "reg-x".
The chapter starts with the basics of regular expressions and the most useful stringr functions for data analysis.
We'll then expand your knowledge of patterns, to cover seven important new topics (escaping, anchoring, character classes, shorthand classes, quantifiers, precedence, and grouping).
Next we'll talk about some of the other types of pattern that stringr functions can work with, and the various "flags" that allow you to tweak the operation of regular expressions.
We'll finish up with a survey of other places in stringr, the tidyverse, and base R where you might use regexes.
2022-01-06 12:49:31 +08:00
2021-04-21 21:43:19 +08:00
### Prerequisites
2022-01-04 05:25:03 +08:00
This chapter will use regular expressions as provided by the **stringr** package.
2021-04-21 21:43:19 +08:00
```{r}
#| label: setup
#| message: false
2021-04-21 21:43:19 +08:00
library(tidyverse)
library(babynames)
2021-04-21 21:43:19 +08:00
```
2022-10-05 06:34:27 +08:00
## Regular expression basics {#sec-reg-basics}
2022-01-05 07:58:02 +08:00
2022-10-05 06:34:27 +08:00
### Patterns
2022-01-06 12:49:31 +08:00
2022-10-05 06:34:27 +08:00
The simplest patterns consist of regular letters and numbers, and match exactly.
And when we say exact we really mean exact: "x" will only match lowercase "x" not uppercase "X".
2022-10-05 06:34:27 +08:00
To see what's going on we can take advantage of the second argument to `str_view()` a regular expression that's applied to its first argument:
```{r}
2022-10-05 06:34:27 +08:00
str_view(c("x", "X"), "x")
```
2022-10-05 06:34:27 +08:00
In general, any letter or number will match exactly, but punctuation characters like `.`, `+`, `*`, `[`, `]`, `?`, often have special meanings[^regexps-2].
For example, `.`
2022-10-05 06:34:27 +08:00
will match any character[^regexps-3], so `"a."` will match any string that contains an "a" followed by another character
:
2022-10-05 06:34:27 +08:00
[^regexps-2]: You'll learn how to escape this special behaviour in @sec-regexp-escaping.
2022-10-05 06:34:27 +08:00
[^regexps-3]: Well, any character apart from `\n`.
```{r}
2022-10-05 06:34:27 +08:00
str_view(c("a", "ab", "ae", "bd", "ea", "eab"), "a.")
```
**Quantifiers** control how many times an element that can be applied to other pattern: `?` makes a pattern optional (i.e. it matches 0 or 1 times), `+` lets a pattern repeat (i.e. it matches at least once), and `*` lets a pattern be optional or repeat (i.e. it matches any number of times, including 0).
```{r}
# ab? matches an "a", optionally followed by a "b".
2022-10-05 06:34:27 +08:00
str_view(c("a", "ab", "abb"), "ab?")
# ab+ matches an "a", followed by at least one "b".
2022-10-05 06:34:27 +08:00
str_view(c("a", "ab", "abb"), "ab+")
# ab* matches an "a", followed by any number of "b"s.
2022-10-05 06:34:27 +08:00
str_view(c("a", "ab", "abb"), "ab*")
```
**Character classes** are defined by `[]` and let you match a set set of characters, e.g. `[abcd]` matches "a", "b", "c", or "d".
You can also invert the match by starting with `^`: `[^abcd]` matches anything **except** "a", "b", "c", or "d".
2022-10-05 06:34:27 +08:00
We can use this idea to find the vowels and consonants in a few particularly special names:
```{r}
names <- c("Hadley", "Mine", "Garrett")
2022-10-05 06:34:27 +08:00
str_view(names, "[aeiou]")
str_view(names, "[^aeiou]")
```
You can combine character classes and quantifiers.
2022-10-05 06:34:27 +08:00
The following regexp looks for a vowel followed by one or more consonants:
```{r}
2022-10-05 06:34:27 +08:00
str_view(names, "[aeiou][^aeiou]+")
```
2022-10-05 06:34:27 +08:00
You can use **alternation** to pick between one or more alternative patterns.
Here are a few examples:
2022-10-05 06:34:27 +08:00
- Match apple, pear, or banana: `apple|pear|banana`.
- Match three letters or two digits: `\w{3}|\d{2}`.
2022-10-05 06:34:27 +08:00
Regular expressions are very compact and use a lot of punctuation characters, so they can seem overwhelming at first, and you'll think a cat has walked across your keyboard.
So don't worry if they're hard to understand at first; you'll get better with practice.
Lets start that practice with some useful stringr functions.
### Detect matches
2022-10-05 06:34:27 +08:00
`str_detect()` takes a character vector and a pattern, and returns a logical vector that says if the pattern was found at each element of the vector.
```{r}
2022-10-05 06:34:27 +08:00
str_detect(c("a", "b", "c"), "[aeiou]")
```
`str_detect()` returns a logical vector the same length as the first argument, so it pairs well with `filter()`.
For example, this code finds all the most popular names containing a lower-case "x":
```{r}
babynames |>
filter(str_detect(name, "x")) |>
count(name, wt = n, sort = TRUE)
```
2022-10-05 06:34:27 +08:00
We can also use `str_detect()` with `summarize()` by pairing it with `sum()` or `mean()`.
remembering that when you use a logical vector in a numeric context, `FALSE` becomes 0 and `TRUE` becomes 1 so `sum(str_detect(x, pattern))` tells you the number of observations that match and `mean(str_detect(x, pattern))` tells you the proportion of observations that match.
For example, the following snippet computes and visualizes the proportion of baby names that contain "x", broken down by year.
```{r}
#| label: fig-x-names
#| fig-cap: >
#| A time series showing the proportion of baby names that contain a
#| lower case "x".
#| fig-alt: >
#| A timeseries 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.
babynames |>
group_by(year) |>
summarise(prop_x = mean(str_detect(name, "x"))) |>
ggplot(aes(year, prop_x)) +
geom_line()
```
(Note that this gives us the proportion of names that contain an x; if you wanted the proportion of babies with a name containing an x, you'd need to perform a weighted mean.)
### Count matches
A variation on `str_detect()` is `str_count()`: rather than a simple yes or no, it tells you how many matches there are in a string:
```{r}
x <- c("apple", "banana", "pear")
str_count(x, "p")
```
Note that regular expression matches never overlap so `str_count()` only starts looking for a new match after the end of the last match.
For example, in `"abababa"`, how many times will the pattern `"aba"` match?
Regular expressions say two, not three:
```{r}
str_count("abababa", "aba")
2022-10-05 06:34:27 +08:00
str_view("abababa", "aba")
```
It's natural to use `str_count()` with `mutate()`.
2022-10-05 06:34:27 +08:00
The following example uses `str_count()` with character classes to count the number of vowels and consonants in each name.
```{r}
2022-10-05 06:34:27 +08:00
babynames |>
count(name) |>
mutate(
vowels = str_count(name, "[aeiou]"),
consonants = str_count(name, "[^aeiou]")
)
```
2022-10-05 06:34:27 +08:00
If you look closely, you'll notice that there's something off with our calculations: "Aaban" contains three "a"s, but our summary reports only two vowels.
That's because we've forgotten to tell you that regular expressions are case sensitive.
There are three ways we could fix this:
2022-10-05 06:34:27 +08:00
- Add the upper case vowels to the character class: `str_count(name, "[aeiouAEIOU]")`.
- Tell the regular expression to ignore case: `str_count(regex(name, ignore_case = TRUE), "[aeiou]")`. We'll talk about more in @sec-flags..
- Use `str_to_lower()` to convert the names to lower case: `str_count(str_to_lower(name), "[aeiou]")`. You learned about this function in @sec-other-languages.
2022-10-05 06:34:27 +08:00
This is pretty typical when working with strings --- there are often multiple ways to reach your goal, either 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.
```{r}
2022-10-05 06:34:27 +08:00
babynames |>
count(name) |>
mutate(
name = str_to_lower(name),
vowels = str_count(name, "[aeiou]"),
consonants = str_count(name, "[^aeiou]")
)
```
2022-10-05 06:34:27 +08:00
### Replace values
Another powerful tool are `str_replace()` and `str_replace_all()` which allow you to replace either one match or all matches with your own text.
These are particularly useful in `mutate()` when doing data cleaning.
```{r}
2022-10-05 06:34:27 +08:00
x <- c("apple", "pear", "banana")
str_replace_all(x, "[aeiou]", "-")
```
2022-10-05 06:34:27 +08:00
`str_remove()` and `str_remove_all()` are handy shortcuts for `str_replace(x, pattern, "")`.
2022-10-05 06:34:27 +08:00
### Extract variables
2022-10-05 06:34:27 +08:00
The last function comes from tidyr: `separate_regex_wider()`.
This works similarly to `separate_at_wider()` and `separate_by_wider()` but you give it a vector of regular expressions.
The named components become variables and the unnamed components are dropped.
2022-10-05 06:34:27 +08:00
### Exercises
2022-10-05 06:34:27 +08:00
1. Explain why each of these strings don't match a `\`: `"\"`, `"\\"`, `"\\\"`.
2022-10-05 06:34:27 +08:00
2. How would you match the sequence `"'\`?
2022-10-05 06:34:27 +08:00
3. What patterns will the regular expression `\..\..\..` match?
How would you represent it as a string?
2022-10-05 06:34:27 +08:00
4. What name has the most vowels?
What name has the highest proportion of vowels?
(Hint: what is the denominator?)
2022-10-05 06:34:27 +08:00
5. For each of the following challenges, try solving it by using both a single regular expression, and a combination of multiple `str_detect()` calls.
2022-10-05 06:34:27 +08:00
a. Find all words that start or end with `x`.
b. Find all words that start with a vowel and end with a consonant.
c. Are there any words that contain at least one of each different vowel?
2022-10-05 06:34:27 +08:00
6. Replace all forward slashes in a string with backslashes.
2022-10-05 06:34:27 +08:00
7. Implement a simple version of `str_to_lower()` using `str_replace_all()`.
8. Switch the first and last letters in `words`.
Which of those strings are still `words`?
## Pattern language
2022-01-06 12:49:31 +08:00
2022-10-05 06:34:27 +08:00
You learned the basics of the regular expression pattern language in above, and now its time to dig into more of the details.
First, we'll start with **escaping**, which allows you to match characters that the pattern language otherwise treats specially.
Next you'll learn about **anchors**, which allow you to match the start or end of the string.
2022-10-05 06:34:27 +08:00
Then you'll more learn about **character classes** and their shortcuts, which allow you to match any character from a set.
We'll finish up with the final details of **quantifiers**, which control how many times a pattern can match.
2022-01-06 12:49:31 +08:00
2022-08-10 00:43:12 +08:00
The terms we use here are the technical names for each component.
They're not always the most evocative of their purpose, but it's very helpful to know the correct terms if you later want to Google for more details.
2022-01-06 12:49:31 +08:00
2022-10-05 06:34:27 +08:00
We'll concentrate on showing how these patterns work with `str_view()` but remember that you can use them with any of the functions that you learned above.
2022-01-17 10:41:16 +08:00
### Escaping {#sec-regexp-escaping}
2021-04-21 21:43:19 +08:00
2022-10-05 06:34:27 +08:00
What if you want to match a literal `.` as part of a bigger regular expression?
2022-01-10 02:41:42 +08:00
You'll need to use an **escape**, which tells the regular expression you want it to match exactly, not use its special behavior.
Like strings, regexps use the backslash for escaping, so to match a `.`, you need the regexp `\.`.
2021-04-21 21:43:19 +08:00
Unfortunately this creates a problem.
We use strings to represent regular expressions, and `\` is also used as an escape symbol in strings.
2022-01-10 02:41:42 +08:00
So, as the following example shows, to create the regular expression `\.` we need the string `"\\."`.
2021-04-21 21:43:19 +08:00
```{r}
2022-01-04 05:25:03 +08:00
# To create the regular expression \., we need to use \\.
2021-04-21 21:43:19 +08:00
dot <- "\\."
2022-01-10 02:41:42 +08:00
# But the expression itself only contains one \
2021-12-14 04:44:52 +08:00
str_view(dot)
2021-04-21 21:43:19 +08:00
# And this tells R to look for an explicit .
str_view(c("abc", "a.c", "bef"), "a\\.c")
```
2022-08-10 00:43:12 +08:00
In this book, we'll write regular expression as `\.` and strings that represent the regular expression as `"\\."`.
2022-01-04 05:25:03 +08:00
2021-04-21 21:43:19 +08:00
If `\` is used as an escape character in regular expressions, how do you match a literal `\`?
Well you need to escape it, creating the regular expression `\\`.
To create that regular expression, you need to use a string, which also needs to escape `\`.
That means to match a literal `\` you need to write `"\\\\"` --- you need four backslashes to match one!
```{r}
x <- "a\\b"
2021-12-14 04:44:52 +08:00
str_view(x)
2021-04-21 21:43:19 +08:00
str_view(x, "\\\\")
```
Alternatively, you might find it easier to use the raw strings you learned about in @sec-raw-strings).
2022-01-10 02:41:42 +08:00
That lets you to avoid one layer of escaping:
2021-12-14 04:44:52 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(x, r"{\\}")
2021-12-14 04:44:52 +08:00
```
2022-01-04 05:25:03 +08:00
The full set of characters with special meanings that need to be escaped is `.^$\|*+?{}[]()`.
2022-01-10 02:41:42 +08:00
In general, look at punctuation characters with suspicion; if your regular expression isn't matching what you think it should, check if you've used any of these characters.
2022-01-04 05:25:03 +08:00
### Anchors
2021-04-21 21:43:19 +08:00
By default, regular expressions will match any part of a string.
2022-01-06 12:49:31 +08:00
If you want to match at the start of end you need to **anchor** the regular expression using `^` or `$`.
2021-04-21 21:43:19 +08:00
- `^` to match the start of the string.
- `$` to match the end of the string.
```{r}
x <- c("apple", "banana", "pear")
2022-01-05 07:58:02 +08:00
str_view(x, "a") # match "a" anywhere
str_view(x, "^a") # match "a" at start
str_view(x, "a$") # match "a" at end
2021-04-21 21:43:19 +08:00
```
2022-08-10 00:43:12 +08:00
To remember which is which, try this mnemonic which Hadley learned from [Evan Misshula](https://twitter.com/emisshula/status/323863393167613953): if you begin with power (`^`), you end up with money (`$`).
2022-01-06 12:49:31 +08:00
It's tempting to put `$` at the start, because that's how we write sums of money, but it's not what regular expressions want.
2021-04-21 21:43:19 +08:00
2022-01-05 07:58:02 +08:00
To force a regular expression to only match the full string, anchor it with both `^` and `$`:
2021-04-21 21:43:19 +08:00
```{r}
x <- c("apple pie", "apple", "apple cake")
str_view(x, "apple")
str_view(x, "^apple$")
```
2022-01-12 16:08:01 +08:00
You can also match the boundary between words (i.e. the start or end of a word) with `\b`.
2022-08-10 00:43:12 +08:00
This is not that useful in R code, but it can be handy when searching in RStudio.
2022-01-10 02:41:42 +08:00
It's useful to find the name of a function that's a component of other functions.
2022-08-10 00:43:12 +08:00
For example, if to find all uses of `sum()`, you can search for `\bsum\b` to avoid matching `summarise`, `summary`, `rowsum` and so on:
2021-04-21 21:43:19 +08:00
2021-12-14 04:44:52 +08:00
```{r}
x <- c("summary(x)", "summarise(df)", "rowsum(x)", "sum(x)")
str_view(x, "sum")
2022-01-04 05:25:03 +08:00
str_view(x, "\\bsum\\b")
2021-12-14 04:44:52 +08:00
```
2022-10-05 06:34:27 +08:00
When used alone anchors will produce a zero-width match:
```{r}
2022-10-05 06:34:27 +08:00
str_view("abc", c("$", "^", "\\b"))
```
2022-01-05 07:58:02 +08:00
### Character classes
2021-04-21 21:43:19 +08:00
2022-01-10 02:41:42 +08:00
A **character class**, or character **set**, allows you to match any character in a set.
The basic syntax lists each character you want to match inside of `[]`, so `[abc]` will match a, b, or c.
Inside of `[]` only `-`, `^`, and `\` have special meanings:
2021-04-21 21:43:19 +08:00
- `-` defines a range. `[a-z]`: matches any lower case letter and `[0-9]` matches any number.
2022-01-10 02:41:42 +08:00
- `^` takes the inverse of the set. `[^abc]`: matches anything except a, b, or c.
- `\` escapes special characters, so `[\^\-\]]`: matches `^`, `-`, or `]`.
2021-04-21 21:43:19 +08:00
2022-01-04 05:25:03 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view("abcd12345-!@#%.", c("[abc]", "[a-z]", "[^a-z0-9]"))
2022-01-12 16:08:01 +08:00
# You need an escape to match characters that are otherwise
# special inside of []
2022-10-05 06:34:27 +08:00
str_view("a-b-c", "[a\\-c]")
2022-01-04 05:25:03 +08:00
```
2021-04-21 21:43:19 +08:00
2022-01-10 02:41:42 +08:00
Remember that regular expressions are case sensitive so if you want to match any lowercase or uppercase letter, you'd need to write `[a-zA-Z0-9]`.
2022-01-05 07:58:02 +08:00
### Shorthand character classes
2021-04-21 21:43:19 +08:00
2022-01-12 16:08:01 +08:00
There are a few character classes that are used so commonly that they get their own shortcut.
2021-04-21 21:43:19 +08:00
You've already seen `.`, which matches any character apart from a newline.
2022-01-12 16:08:01 +08:00
There are three other particularly useful pairs:
2021-04-21 21:43:19 +08:00
2022-01-17 10:41:16 +08:00
- `\d`: matches any digit;\
`\D`: matches anything that isn't a digit.
2022-01-17 10:41:16 +08:00
- `\s`: matches any whitespace (e.g. space, tab, newline);\
`\S`: matches anything that isn't whitespace.
- `\w`: matches any "word" character, i.e. letters and numbers;\
`\W`: matches any "non-word" character.
2021-04-21 21:43:19 +08:00
Remember, to create a regular expression containing `\d` or `\s`, you'll need to escape the `\` for the string, so you'll type `"\\d"` or `"\\s"`.
2022-10-05 06:34:27 +08:00
2022-01-12 16:08:01 +08:00
The following code demonstrates the different shortcuts with a selection of letters, numbers, and punctuation characters.
2021-04-21 21:43:19 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view("abcd 12345 !@#%.", "\\d+")
str_view("abcd 12345 !@#%.", "\\D+")
str_view("abcd 12345 !@#%.", "\\w+")
str_view("abcd 12345 !@#%.", "\\W+")
str_view("abcd 12345 !@#%.", "\\s+")
str_view("abcd 12345 !@#%.", "\\S+")
2021-04-21 21:43:19 +08:00
```
2022-01-04 05:25:03 +08:00
### Quantifiers
2021-04-21 21:43:19 +08:00
2022-01-10 02:41:42 +08:00
The **quantifiers** control how many times a pattern matches.
2022-10-05 06:34:27 +08:00
In @sec-reg-basics you learned about `?` (0 or 1 matches), `+` (1 or more matches), and `*` (0 or more matches).
2022-01-12 16:08:01 +08:00
For example, `colou?r` will match American or British spelling, `\d+` will match one or more digits, and `\s?` will optionally match a single whitespace.
2021-04-21 21:43:19 +08:00
You can also specify the number of matches precisely:
- `{n}`: exactly n
- `{n,}`: n or more
- `{n,m}`: between n and m
2022-01-17 10:41:16 +08:00
The following code shows how this works for a few simple examples using to `\b` match the start or end of a word.
2021-04-21 21:43:19 +08:00
```{r}
2022-01-12 16:08:01 +08:00
x <- " x xx xxx xxxx"
2022-10-05 06:34:27 +08:00
str_view(x, "\\bx{2}")
str_view(x, "\\bx{2,}")
str_view(x, "\\bx{1,3}")
str_view(x, "\\bx{2,3}")
2021-04-21 21:43:19 +08:00
```
2022-10-05 06:34:27 +08:00
### Operator precedence and parentheses
2022-01-05 07:58:02 +08:00
What does `ab+` match?
2022-01-12 16:08:01 +08:00
Does it match "a" followed by one or more "b"s, or does it match "ab" repeated any number of times?
What does `^a|b$` 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"?
The answer to these questions is determined by operator precedence, similar to the PEMDAS or BEDMAS rules you might have learned in school for what `a + b * c`.
2022-01-12 16:08:01 +08:00
You already know that `a + b * c` is equivalent to `a + (b * c)` not `(a + b) * c` because `*` has high precedence and `+` has lower precedence: you compute `*` before `+`.
In regular expressions, quantifiers have high precedence and alternation has low precedence.
That means `ab+` is equivalent to `a(b+)`, and `^a|b$` is equivalent to `(^a)|(b$)`.
2022-10-05 06:34:27 +08:00
Just like with algebra, you can use parentheses to override the usual order.
Unlike algebra you're unlikely to remember the precedence rules for regexes, so feel free to use parentheses liberally.
2022-01-12 16:08:01 +08:00
Technically the escape, character classes, and parentheses are all operators that also have precedence.
But these tend to be less likely to cause confusion because they mostly behave how you expect: it's unlikely that you'd think that `\(s|d)` would mean `(\s)|(\d)`.
2022-01-05 07:58:02 +08:00
2022-10-05 06:34:27 +08:00
### Grouping and capturing
Parentheses are an important tool for controlling the order in which pattern operations are applied but they also have an important additional effect: they create **capturing groups** that allow you to use to sub-components of the match.
You can refer back to previously matched text inside parentheses by using **back reference**: `\1` refers to the match contained in the first parenthesis, `\2` in the second parenthesis, and so on.
For example, the following pattern finds all fruits that have a repeated pair of letters:
```{r}
str_view(fruit, "(..)\\1")
```
And this one finds all words that start and end with the same pair of letters:
```{r}
str_view(words, "^(..).*\\1$")
```
You can also use backreferences in `str_replace()`:
```{r}
sentences |>
str_replace("(\\w+) (\\w+) (\\w+)", "\\1 \\3 \\2") |>
head(5)
```
If you want extract the matches for each group you can use `str_match()`.
But it returns a matrix, so isn't as easy to work with:
```{r}
sentences |>
str_match("the (\\w+) (\\w+)") |>
head()
```
You could convert to a tibble and name the columns:
```{r}
sentences |>
str_match("the (\\w+) (\\w+)") |>
as_tibble(.name_repair = "minimal") |>
set_names("match", "word1", "word2")
```
But then you've basically recreated your own simple version of `separate_regex_wider()`.
Indeed, behind the scenes `separate_regexp_wider()` converts your vector of patterns to a single regexp that uses grouping to capture only the named components.
Occasionally, you'll want to use parentheses without creating matching groups.
You can create a non-capturing group with `(?:)`.
```{r}
x <- c("a gray cat", "a grey dog")
str_match(x, "(gr(e|a)y)")
str_match(x, "(gr(?:e|a)y)")
```
2021-04-21 21:43:19 +08:00
### Exercises
2022-01-04 05:25:03 +08:00
1. How would you match the literal string `"$^$"`?
2. Given the corpus of common words in `stringr::words`, create regular expressions that find all words that:
a. Start with "y".
b. Don't start with "y".
c. End with "x".
d. Are exactly three letters long. (Don't cheat by using `str_length()`!)
e. Have seven letters or more.
2021-04-21 21:43:19 +08:00
2022-10-05 06:34:27 +08:00
3. Create 11 regular expressions that match the British or American spellings for each of the following words: grey/gray, modelling/modeling, summarize/summarise, aluminium/aluminum, defence/defense, analog/analogue, center/centre, sceptic/skeptic, aeroplane/airplane, arse/ass, doughnut/donut.
Try and make the shortest possible regex!
2022-01-06 12:49:31 +08:00
2022-10-05 06:34:27 +08:00
4. Create a regular expression that will match telephone numbers as commonly written in your country.
2022-01-04 05:25:03 +08:00
2022-10-05 06:34:27 +08:00
5. Write the equivalents of `?`, `+`, `*` in `{m,n}` form.
2022-01-04 05:25:03 +08:00
2022-10-05 06:34:27 +08:00
6. 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.)
2021-04-21 21:43:19 +08:00
a. `^.*$`
b. `"\\{.+\\}"`
c. `\d{4}-\d{2}-\d{2}`
d. `"\\\\{4}"`
2022-10-05 06:34:27 +08:00
7. Describe, in words, what these expressions will match:
a. `(.)\1\1`
b. `"(.)(.)\\2\\1"`
c. `(..)\1`
d. `"(.).\\1.\\1"`
e. `"(.)(.)(.).*\\3\\2\\1"`
8. Construct regular expressions to match words that:
a. Who's first letter is the same as the last letter, and the second letter is the same as the second to last letter.
b. Contain one letter repeated in at least three places (e.g. "eleven" contains three "e"s.)
9. Solve the beginner regexp crosswords at <https://regexcrossword.com/challenges/beginner>.
## Pattern control
Now that you've learn about regular expressions, you might be worried about them working when you don't want them to.
### Fixed matches
You can opt-out of the regular expression rules by using `fixed()`:
```{r}
str_view(c("", "a", "."), fixed("."))
```
You can opt out by setting `ignore_case = TRUE`.
```{r}
str_view("x X xy", "X")
str_view("x X xy", fixed("X", ignore_case = TRUE))
```
### Regex Flags {#sec-flags}
The are a number of settings, often called **flags** in other programming languages, that you can use to control some of the details of the regex.
In stringr, you can use these by wrapping the pattern in a call to `regex()`:
```{r}
#| eval: false
# The regular call:
str_view(fruit, "nana")
# is shorthand for
str_view(fruit, regex("nana"))
```
The most useful flag is probably `ignore_case = TRUE` because it allows characters to match either their uppercase or lowercase forms:
```{r}
bananas <- c("banana", "Banana", "BANANA")
str_view(bananas, "banana")
str_view(bananas, regex("banana", ignore_case = TRUE))
```
If you're doing a lot of work with multiline strings (i.e. strings that contain `\n`), `multiline` and `dotall` can also be useful.
`dotall = TRUE` allows `.` to match everything, including `\n`:
```{r}
x <- "Line 1\nLine 2\nLine 3"
str_view(x, ".L")
str_view(x, regex(".L", dotall = TRUE))
```
And `multiline = TRUE` allows `^` and `$` to match the start and end of each line rather than the start and end of the complete string:
```{r}
x <- "Line 1\nLine 2\nLine 3"
str_view(x, "^Line")
str_view(x, regex("^Line", multiline = TRUE))
```
Finally, if you're writing a complicated regular expression and you're worried you might not understand it in the future, `comments = TRUE` can be extremely useful.
It allows you to use comments and whitespace to make complex regular expressions more understandable.
Spaces and new lines are ignored, as is everything after `#`.
(Note that we use a raw string here to minimize the number of escapes needed.)
```{r}
phone <- 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)
```
If you're using comments and want to match a space, newline, or `#`, you'll need to escape it:
```{r}
str_view("x x #", regex("x #", comments = TRUE))
str_view("x x #", regex(r"(x\ \#)", comments = TRUE))
```
2021-04-21 21:43:19 +08:00
2022-01-12 16:08:01 +08:00
## Practice
To put these ideas in practice we'll solve a few semi-authentic problems using the `words` and `sentences` datasets built into stringr.
`words` is a list of common English words and `sentences` is a set of simple sentences originally used for testing voice transmission.
```{r}
str_view(head(words))
str_view(head(sentences))
```
2022-01-17 10:41:16 +08:00
The following three sections help you practice the components of a pattern by discussing three general techniques: checking you work by creating simple positive and negative controls, combining regular expressions with Boolean algebra, and creating complex patterns using string manipulation.
### Check your work
First, let's find all sentences that start with "The".
Using the `^` anchor alone is not enough:
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(sentences, "^The")
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
Because it all matches sentences starting with `They` or `Those`.
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:
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(sentences, "^The\\b")
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
What about finding all sentences that begin with a pronoun?
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(sentences, "^She|He|It|They\\b")
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
A quick inspection of the results shows that we're getting some spurious matches.
2022-08-10 00:43:12 +08:00
That's because we've forgotten to use parentheses:
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(sentences, "^(She|He|It|They)\\b")
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
You might wonder how you might spot such a mistake if it didn't occur in the first few matches.
A good technique is to create a few positive and negative matches and use them to test that you pattern works as expected.
2022-01-12 16:08:01 +08:00
```{r}
2022-01-17 10:41:16 +08:00
pos <- c("He is a boy", "She had a good time")
neg <- c("Shells come from the sea", "Hadley said 'It's a great day'")
pattern <- "^(She|He|It|They)\\b"
str_detect(pos, pattern)
str_detect(neg, pattern)
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
It's typically much easier to come up with positive examples than negative examples, because it takes some time until you're good enough with regular expressions to predict where your weaknesses are.
Nevertheless they're still useful; even if you don't get them correct right away, you can slowly accumulate them as you work on your problem.
If you later get more into programming and learn about unit tests, you can then turn these examples into automated tests that ensure you never make the same mistake twice.)
2022-01-12 16:08:01 +08:00
### Boolean operations {#sec-boolean-operations}
2022-01-12 16:08:01 +08:00
2022-01-17 10:41:16 +08:00
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 (`[^aeiou]`), then allow that to match any number of letters (`[^aeiou]+`), then force it to match the whole string by anchoring to the beginning and the end (`^[^aeiou]+$`):
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(words, "^[^aeiou]+$")
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
But we 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 don't contain any vowels:
2022-01-12 16:08:01 +08:00
```{r}
2022-01-17 10:41:16 +08:00
words[!str_detect(words, "[aeiou]")]
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
This is a useful technique whenever you're 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".
There's 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":
2022-01-12 16:08:01 +08:00
```{r}
2022-01-17 10:41:16 +08:00
words[str_detect(words, "a.*b|b.*a")]
2022-01-12 16:08:01 +08:00
```
2022-08-17 00:39:29 +08:00
It's simpler to combine the results of two calls to `str_detect()`:
2022-01-12 16:08:01 +08:00
```{r}
2022-01-17 10:41:16 +08:00
words[str_detect(words, "a") & str_detect(words, "b")]
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
What if we wanted to see if there was a word that contains all vowels?
If we did it with patterns we'd need to generate 5!
(120) different patterns:
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
#| results: false
2022-01-17 10:41:16 +08:00
words[str_detect(words, "a.*e.*i.*o.*u")]
# ...
words[str_detect(words, "u.*o.*i.*e.*a")]
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
It's much simpler to combine six calls to `str_detect()`:
2022-01-12 16:08:01 +08:00
```{r}
words[
str_detect(words, "a") &
str_detect(words, "e") &
str_detect(words, "i") &
str_detect(words, "o") &
str_detect(words, "u")
]
```
2022-01-17 10:41:16 +08:00
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.
### Creating a pattern with code
What if we wanted to find all `sentences` that mention a color?
The basic idea is simple: we just combine alternation with word boundaries.
2022-01-12 16:08:01 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(sentences, "\\b(red|green|blue)\\b")
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
But it would be tedious to construct this pattern by hand.
Wouldn't it be nice if we could store the colours in a vector?
2022-01-12 16:08:01 +08:00
```{r}
2022-01-17 10:41:16 +08:00
rgb <- c("red", "green", "blue")
```
2022-01-12 16:08:01 +08:00
2022-01-17 10:41:16 +08:00
Well, we can!
We'd just need to create the pattern from the vector using `str_c()` and `str_flatten()`:
2022-01-17 10:41:16 +08:00
```{r}
str_c("\\b(", str_flatten(rgb, "|"), ")\\b")
```
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 colours that R can use for plots:
```{r}
2022-10-05 06:34:27 +08:00
str_view(colors())[1:27]
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
But first lets element the numbered variants:
2022-01-12 16:08:01 +08:00
```{r}
2022-01-17 10:41:16 +08:00
cols <- colors()
cols <- cols[!str_detect(cols, "\\d")]
cols[1:27]
2022-01-17 10:41:16 +08:00
```
2022-01-12 16:08:01 +08:00
2022-01-17 10:41:16 +08:00
Then we can turn this into one giant pattern:
```{r}
pattern <- str_c("\\b(", str_flatten(cols, "|"), ")\\b")
2022-10-05 06:34:27 +08:00
str_view(sentences, pattern)
2022-01-12 16:08:01 +08:00
```
2022-01-17 10:41:16 +08:00
In this example `cols` only contains numbers and letters so you don't need to worry about metacharacters.
But in general, when creating patterns from existing strings it's good practice to run through `str_escape()` which will automatically add `\` in front of otherwise special characters.
### Exercises
1. Construct patterns to find evidence for and against the rule "i before e except after c"?
2022-10-05 06:34:27 +08:00
2. `colors()` contains a number of modifiers like "lightgray" and "darkblue". How could you automatically identify these modifiers? (Think about how you might detect and removed what colors are being modified).
3. Create a regular expression that finds any base R dataset. You can get a list of these datasets via a special use of the `data()` function: `data(package = "datasets")$results[, "Item"]`. Note that a number of old datasets are individual vectors; these contain the name of the grouping "data frame" in parentheses, so you'll need to also strip these off.
2022-01-12 16:08:01 +08:00
2022-10-05 06:34:27 +08:00
## Elsewhere
2022-01-04 05:25:03 +08:00
2022-10-05 06:34:27 +08:00
The are a bunch of other places you can use regular expressions outside of stringr.
2022-01-04 05:25:03 +08:00
2022-10-05 06:34:27 +08:00
### stringr
2022-10-05 06:34:27 +08:00
- `str_locate()`, `str_locate_all()`
- `str_split()` and friends
- `str_extract()`
2022-01-04 05:25:03 +08:00
2022-10-05 06:34:27 +08:00
### tidyverse
2022-01-05 07:58:02 +08:00
2022-10-05 06:34:27 +08:00
- `matches()`: a "tidyselect" function that you can use anywhere in the tidyverse when selecting variables (e.g. `dplyr::select()`, `rename_with()`, `across()`, ...).
2022-10-05 06:34:27 +08:00
- `names_pattern` in `pivot_longer()`
2022-10-05 06:34:27 +08:00
- `sep` in `separate_by_longer()` and `separate_by_wider()`.
2022-10-05 06:34:27 +08:00
### Base R
2022-10-05 06:34:27 +08:00
The regular expressions used by stringr are very slightly different to those of base R.
That's because stringr is built on top of the [stringi package](https://stringi.gagolewski.com), which is in turn built on top of the [ICU engine](https://unicode-org.github.io/icu/userguide/strings/regexp.html), whereas base R functions (like `gsub()` and `grepl()`) use either the [TRE engine](https://github.com/laurikari/tre) or the [PCRE engine](https://www.pcre.org).
Fortunately, the basics of regular expressions are so well established that you'll encounter few variations when working with the patterns you'll learn in this book (and we'll point them out where important).
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 `(?…)` syntax.
You can learn more about these advanced features in `vignette("regular-expressions", package = "stringr")`.
- `apropos()` searches all objects available from the global environment.
This is useful if you can't quite remember the name of the function.
```{r}
apropos("replace")
```
- `dir()` lists all the files in a directory.
The `pattern` argument takes a regular expression and only returns file names that match the pattern.
For example, you can find all the R Markdown files in the current directory with:
```{r}
head(dir(pattern = "\\.Rmd$"))
```
(If you're more comfortable with "globs" like `*.Rmd`, you can convert them to regular expressions with `glob2rx()`).
2022-10-05 06:34:27 +08:00
## Summary
Another useful reference is [https://www.regular-expressions.info/](https://www.regular-expressions.info/tutorial.html).
It's not R specific, but it covers the most advanced features and explains how regular expressions work under the hood.