2022-05-14 04:46:49 +08:00
# Regular expressions {#sec-regular-expressions}
2021-04-21 21:43:19 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| echo: false
2023-07-13 23:52:21 +08:00
2022-05-14 04:46:49 +08:00
source("_common.R")
2021-05-04 21:10:39 +08:00
```
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.
2023-01-03 15:06:27 +08:00
This chapter will focus on functions that use **regular expressions**, a concise and powerful language for describing patterns within strings.
2022-11-10 04:47:46 +08:00
The term "regular expression" is a bit of a mouthful, so most people abbreviate it to "regex"[^regexps-1] or "regexp".
2022-01-04 05:25:03 +08:00
2022-11-10 04:47:46 +08:00
[^regexps-1]: You can pronounce it with either a hard-g (reg-x) or a soft-g (rej-x).
2022-10-05 06:34:27 +08:00
The chapter starts with the basics of regular expressions and the most useful stringr functions for data analysis.
2022-11-10 04:47:46 +08:00
We'll then expand your knowledge of patterns and cover seven important new topics (escaping, anchoring, character classes, shorthand classes, quantifiers, precedence, and grouping).
2023-01-03 15:06:27 +08:00
Next, we'll 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.
We'll finish with a survey of other places in 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-10-06 05:55:47 +08:00
In this chapter, we'll use regular expression functions from stringr and tidyr, both core members of the tidyverse, as well as data from the babynames package.
2021-04-21 21:43:19 +08:00
2022-05-14 04:46:49 +08:00
```{r}
#| label: setup
#| message: false
2021-04-21 21:43:19 +08:00
library(tidyverse)
2022-10-04 05:32:07 +08:00
library(babynames)
2021-04-21 21:43:19 +08:00
```
2023-01-03 15:06:27 +08:00
Through this chapter, we'll 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:
2022-10-06 05:55:47 +08:00
- `fruit` contains the names of 80 fruits.
- `words` contains 980 common English words.
- `sentences` contains 720 short sentences.
2022-11-04 21:21:06 +08:00
## Pattern basics {#sec-reg-basics}
2022-10-06 05:55:47 +08:00
2022-11-10 04:47:46 +08:00
We'll use `str_view()` to learn how regex patterns work.
2022-12-07 00:51:11 +08:00
We used `str_view()` in the last chapter to better understand a string vs. its printed representation, and now we'll use it with its second argument, a regular expression.
2022-11-10 04:47:46 +08:00
When this is supplied, `str_view()` will show only the elements of the string vector that match, surrounding each match with `<>`, and, where possible, highlighting the match in blue.
2022-01-06 12:49:31 +08:00
2022-11-10 04:47:46 +08:00
The simplest patterns consist of letters and numbers which match those characters exactly:
2022-10-04 05:32:07 +08:00
```{r}
2022-10-06 05:55:47 +08:00
str_view(fruit, "berry")
2022-10-04 05:32:07 +08:00
```
2022-11-10 04:47:46 +08:00
Letters and numbers match exactly and are called **literal characters**.
2023-05-21 12:07:34 +08:00
Most punctuation characters, like `.`, `+`, `*`, `[`, `]`, and `?`, have special meanings[^regexps-2] and are called **metacharacters**. 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-04 05:32:07 +08:00
:
2022-11-04 21:21:06 +08:00
[^regexps-2]: You'll learn how to escape these special meanings in @sec-regexp-escaping.
2022-10-04 05:32:07 +08:00
2022-10-05 06:34:27 +08:00
[^regexps-3]: Well, any character apart from `\n`.
2022-10-04 05:32:07 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view(c("a", "ab", "ae", "bd", "ea", "eab"), "a.")
2022-10-04 05:32:07 +08:00
```
2022-10-06 05:55:47 +08:00
Or we could find all the fruits that contain an "a", followed by three letters, followed by an "e":
```{r}
str_view(fruit, "a...e")
```
2022-11-10 04:47:46 +08:00
**Quantifiers** control how many times a pattern can match:
2023-01-27 23:51:22 +08:00
- `?` makes a pattern optional (i.e. it matches 0 or 1 times)
- `+` lets a pattern repeat (i.e. it matches at least once)
- `*` lets a pattern be optional or repeat (i.e. it matches any number of times, including 0).
2022-10-04 05:32:07 +08:00
```{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?")
2022-10-04 05:32:07 +08:00
# 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+")
2022-10-04 05:32:07 +08:00
# 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*")
2022-10-04 05:32:07 +08:00
```
2023-04-10 23:22:08 +08:00
**Character classes** are defined by `[]` and let you match a set of characters, e.g., `[abcd]` matches "a", "b", "c", or "d".
2022-10-04 05:32:07 +08:00
You can also invert the match by starting with `^`: `[^abcd]` matches anything **except** "a", "b", "c", or "d".
2023-02-28 06:42:29 +08:00
We can use this idea to find the words containing an "x" surrounded by vowels, or a "y" surrounded by consonants:
2022-10-04 05:32:07 +08:00
```{r}
2023-02-28 06:42:29 +08:00
str_view(words, "[aeiou]x[aeiou]")
str_view(words, "[^aeiou]y[^aeiou]")
2022-10-04 05:32:07 +08:00
```
2023-02-28 06:42:29 +08:00
You can use **alternation**, `|`, to pick between one or more alternative patterns.
For example, the following patterns look for fruits containing "apple", "melon", or "nut", or a repeated vowel.
2022-10-04 05:32:07 +08:00
```{r}
2023-02-28 06:42:29 +08:00
str_view(fruit, "apple|melon|nut")
2022-10-06 05:55:47 +08:00
str_view(fruit, "aa|ee|ii|oo|uu")
```
2022-10-04 05:32:07 +08:00
2022-10-06 05:55:47 +08:00
Regular expressions are very compact and use a lot of punctuation characters, so they can seem overwhelming and hard to read at first.
Don't worry; you'll get better with practice, and simple patterns will soon become second nature.
2022-11-10 04:47:46 +08:00
Let's kick off that process by practicing with some useful stringr functions.
2022-10-04 05:32:07 +08:00
2022-11-07 22:32:57 +08:00
## Key functions {#sec-stringr-regex-funs}
2022-11-04 21:21:06 +08:00
2022-11-10 04:47:46 +08:00
Now that you've got the basics of regular expressions under your belt, let's use them with some stringr and tidyr functions.
2023-01-03 15:06:27 +08:00
In the following section, you'll 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.
2022-11-04 21:21:06 +08:00
2022-10-04 05:32:07 +08:00
### Detect matches
2023-01-03 15:06:27 +08:00
`str_detect()` returns a logical vector that is `TRUE` if the pattern matches an element of the character vector and `FALSE` otherwise:
2022-10-04 05:32:07 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_detect(c("a", "b", "c"), "[aeiou]")
2022-10-04 05:32:07 +08:00
```
2022-11-10 04:47:46 +08:00
Since `str_detect()` returns a logical vector of the same length as the initial vector, it pairs well with `filter()`.
2022-10-04 05:32:07 +08:00
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-11-04 21:21:06 +08:00
We can also use `str_detect()` with `summarize()` by pairing it with `sum()` or `mean()`: `sum(str_detect(x, pattern))` tells you the number of observations that match and `mean(str_detect(x, pattern))` tells you the proportion that match.
For example, the following snippet computes and visualizes the proportion of baby names[^regexps-4] that contain "x", broken down by year.
2022-10-06 05:55:47 +08:00
It looks like they've radically increased in popularity lately!
2022-10-04 05:32:07 +08:00
2022-11-04 21:21:06 +08:00
[^regexps-4]: 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.
2022-10-04 05:32:07 +08:00
```{r}
2023-05-26 23:44:08 +08:00
#| fig-alt: |
2023-01-03 15:06:27 +08:00
#| A time series showing the proportion of baby names that contain the letter x.
2022-10-04 05:32:07 +08:00
#| 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) |>
2022-11-19 06:07:54 +08:00
summarize(prop_x = mean(str_detect(name, "x"))) |>
2022-12-13 02:35:15 +08:00
ggplot(aes(x = year, y = prop_x)) +
2022-10-04 05:32:07 +08:00
geom_line()
```
2023-03-09 11:02:03 +08:00
There are two functions that are closely related to `str_detect()`: `str_subset()` and `str_which()`.
`str_subset()` returns a character vector containing only the strings that match.
`str_which()` returns an integer vector giving the positions of the strings that match.
2022-10-04 05:32:07 +08:00
### Count matches
2023-03-09 11:02:03 +08:00
The next step up in complexity from `str_detect()` is `str_count()`: rather than a true or false, it tells you how many matches there are in each string.
2022-10-04 05:32:07 +08:00
```{r}
x <- c("apple", "banana", "pear")
str_count(x, "p")
```
2023-03-09 11:02:03 +08:00
Note that each match starts at the end of the previous match, i.e. regex matches never overlap.
2022-10-04 05:32:07 +08:00
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")
2022-10-04 05:32:07 +08:00
```
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.
2022-10-04 05:32:07 +08:00
```{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-04 05:32:07 +08:00
```
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.
2022-10-06 05:55:47 +08:00
That's because regular expressions are case sensitive.
2022-10-05 06:34:27 +08:00
There are three ways we could fix this:
2022-10-04 05:32:07 +08:00
2022-10-05 06:34:27 +08:00
- Add the upper case vowels to the character class: `str_count(name, "[aeiouAEIOU]")`.
2023-05-10 11:02:42 +08:00
- Tell the regular expression to ignore case: `str_count(name, regex("[aeiou]", ignore_case = TRUE))`. We'll talk about more in @sec-flags.
2023-01-03 15:06:27 +08:00
- Use `str_to_lower()` to convert the names to lower case: `str_count(str_to_lower(name), "[aeiou]")`.
2022-10-04 05:32:07 +08:00
2022-11-04 21:21:06 +08:00
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.
2022-10-05 06:34:27 +08:00
If you get stuck trying one approach, it can often be useful to switch gears and tackle the problem from a different perspective.
2022-10-04 05:32:07 +08:00
2022-10-06 05:55:47 +08:00
In this case, since we're applying two functions to the name, I think it's easier to transform it first:
2022-10-04 05:32:07 +08:00
```{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-04 05:32:07 +08:00
```
2022-10-05 06:34:27 +08:00
### Replace values
2022-11-04 21:21:06 +08:00
As well as detecting and counting matches, we can also modify them with `str_replace()` and `str_replace_all()`.
`str_replace()` replaces the first match, and as the name suggests, `str_replace_all()` replaces all matches.
2022-10-04 05:32:07 +08:00
```{r}
2022-10-05 06:34:27 +08:00
x <- c("apple", "pear", "banana")
str_replace_all(x, "[aeiou]", "-")
2022-10-04 05:32:07 +08:00
```
2023-03-09 11:02:03 +08:00
`str_remove()` and `str_remove_all()` are handy shortcuts for `str_replace(x, pattern, "")`:
2022-10-04 05:32:07 +08:00
2022-10-06 05:55:47 +08:00
```{r}
x <- c("apple", "pear", "banana")
str_remove_all(x, "[aeiou]")
```
2022-11-10 04:47:46 +08:00
These functions are naturally paired with `mutate()` when doing data cleaning, and you'll often apply them repeatedly to peel off layers of inconsistent formatting.
2022-10-06 05:55:47 +08:00
2022-12-07 06:06:36 +08:00
### Extract variables {#sec-extract-variables}
2022-10-04 05:32:07 +08:00
2022-11-10 02:47:28 +08:00
The last function we'll discuss uses regular expressions to extract data out of one column into one or more new columns: `separate_wider_regex()`.
2023-01-23 22:35:09 +08:00
It's a peer of the `separate_wider_position()` and `separate_wider_delim()` functions that you learned about in @sec-string-columns.
These functions live in tidyr because they operate on (columns of) data frames, rather than individual vectors.
2022-11-04 21:21:06 +08:00
2022-11-07 22:32:57 +08:00
Let's create a simple dataset to show how it works.
Here we have some data derived from `babynames` where we have the name, gender, and age of a bunch of people in a rather weird format[^regexps-5]:
[^regexps-5]: We wish we could reassure you that you'd never see something this weird in real life, but unfortunately over the course of your career you're likely to see much weirder!
```{r}
df <- tribble(
~str,
"<Sheryl>-F_34",
"<Kisha>-F_45",
"<Brandon>-N_33",
"<Sharon>-F_38",
"<Penny>-F_58",
"<Justin>-M_41",
"<Patricia>-F_84",
)
```
To extract this data using `separate_wider_regex()` 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:
```{r}
df |>
separate_wider_regex(
str,
patterns = c(
2023-02-28 06:42:29 +08:00
"<",
name = "[A-Za-z]+",
">-",
2022-11-07 22:32:57 +08:00
gender = ".", "_",
age = "[0-9]+"
)
)
```
If the match fails, you can use `too_short = "debug"` to figure out what went wrong, just like `separate_wider_delim()` and `separate_wider_position()`.
2022-10-04 05:32:07 +08:00
2022-10-05 06:34:27 +08:00
### Exercises
2022-10-04 05:32:07 +08:00
2022-11-04 21:21:06 +08:00
1. What baby name has the most vowels?
2022-10-05 06:34:27 +08:00
What name has the highest proportion of vowels?
(Hint: what is the denominator?)
2022-10-04 05:32:07 +08:00
2023-02-28 06:42:29 +08:00
2. Replace all forward slashes in `"a/b/c/d/e"` with backslashes.
What happens if you attempt to undo the transformation by replacing all backslashes with forward slashes?
(We'll discuss the problem very soon.)
2022-10-04 05:32:07 +08:00
2022-11-04 21:21:06 +08:00
3. Implement a simple version of `str_to_lower()` using `str_replace_all()`.
2022-10-04 05:32:07 +08:00
2022-11-07 22:32:57 +08:00
4. Create a regular expression that will match telephone numbers as commonly written in your country.
2022-10-04 05:32:07 +08:00
2022-11-04 21:21:06 +08:00
## Pattern details
2022-01-06 12:49:31 +08:00
2023-05-21 12:07:34 +08:00
Now that you understand the basics of the pattern language and how to use it with some stringr and tidyr functions, it's time to dig into more of the details.
2022-11-07 23:50:57 +08:00
First, we'll start with **escaping**, which allows you to match metacharacters that would otherwise be treated specially.
2022-11-10 04:47:46 +08:00
Next, you'll learn about **anchors** which allow you to match the start or end of the string.
2023-05-21 12:07:34 +08:00
Then, you'll learn more about **character classes** and their shortcuts which allow you to match any character from a set.
2022-11-10 04:47:46 +08:00
Next, you'll learn the final details of **quantifiers** which control how many times a pattern can match.
Then, we have to cover the important (but complex) topic of **operator precedence** and parentheses.
2022-10-06 05:55:47 +08:00
And we'll finish off with some details of **grouping** components of the pattern.
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.
2022-01-09 03:59:59 +08:00
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-05-14 04:46:49 +08:00
### Escaping {#sec-regexp-escaping}
2021-04-21 21:43:19 +08:00
2023-03-09 11:02:03 +08:00
In order to match a literal `.`, you need an **escape** which tells the regular expression to match metacharacters[^regexps-6] literally.
2022-11-10 04:47:46 +08:00
Like strings, regexps use the backslash for escaping.
2023-03-09 11:02:03 +08:00
So, to match a `.`, you need the regexp `\.`. Unfortunately this creates a problem.
2021-04-21 21:43:19 +08:00
We use strings to represent regular expressions, and `\` is also used as an escape symbol in strings.
2022-11-07 23:50:57 +08:00
So to create the regular expression `\.` we need the string `"\\."`, as the following example shows.
2021-04-21 21:43:19 +08:00
2023-03-09 11:02:03 +08:00
[^regexps-6]: The complete set of metacharacters is `.^$\|*+?{}[]()`
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-11-04 21:21:06 +08:00
In this book, we'll usually write regular expression without quotes, like `\.`.
If we need to emphasize what you'll actually type, we'll surround it with quotes and add extra escapes, like `"\\."`.
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 `\`?
2022-11-10 04:47:46 +08:00
Well, you need to escape it, creating the regular expression `\\`.
2021-04-21 21:43:19 +08:00
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, "\\\\")
```
2022-05-14 04:46:49 +08:00
Alternatively, you might find it easier to use the raw strings you learned about in @sec-raw-strings).
2023-05-21 12:07:34 +08:00
That lets you 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-11-10 04:37:55 +08:00
If you're trying to match a literal `.`, `$`, `|`, `*`, `+`, `?`, `{`, `}`, `(`, `)`, there's an alternative to using a backslash escape: you can use a character class: `[.]`, `[$]`, `[|]`, \...
all match the literal values.
```{r}
str_view(c("abc", "a.c", "a*c", "a c"), "a[.]c")
str_view(c("abc", "a.c", "a*c", "a c"), ".[*]c")
```
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.
2023-04-17 20:07:22 +08:00
If you want to match at the start or end you need to **anchor** the regular expression using `^` to match the start or `$` to match the end:
2021-04-21 21:43:19 +08:00
```{r}
2022-10-06 22:05:13 +08:00
str_view(fruit, "^a")
str_view(fruit, "a$")
2021-04-21 21:43:19 +08:00
```
2023-03-09 11:02:03 +08:00
It's tempting to think that `$` should match the start of a string, because that's how we write dollar amounts, but that's not what regular expressions want.
2021-04-21 21:43:19 +08:00
2023-01-23 22:35:09 +08:00
To force a regular expression to match only the full string, anchor it with both `^` and `$`:
2021-04-21 21:43:19 +08:00
```{r}
2022-10-06 05:55:47 +08:00
str_view(fruit, "apple")
str_view(fruit, "^apple$")
2021-04-21 21:43:19 +08:00
```
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`.
2023-01-23 22:35:09 +08:00
This can be particularly useful when using RStudio's find and replace tool.
2022-11-19 06:07:54 +08:00
For example, if to find all uses of `sum()`, you can search for `\bsum\b` to avoid matching `summarize`, `summary`, `rowsum` and so on:
2021-04-21 21:43:19 +08:00
2021-12-14 04:44:52 +08:00
```{r}
2022-11-19 06:07:54 +08:00
x <- c("summary(x)", "summarize(df)", "rowsum(x)", "sum(x)")
2021-12-14 04:44:52 +08:00
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-06 22:05:13 +08:00
When used alone, anchors will produce a zero-width match:
2022-01-18 12:49:41 +08:00
```{r}
2022-10-05 06:34:27 +08:00
str_view("abc", c("$", "^", "\\b"))
2022-01-18 12:49:41 +08:00
```
2022-10-06 05:55:47 +08:00
This helps you understand what happens when you replace a standalone anchor:
```{r}
str_replace_all("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.
2023-02-28 06:42:29 +08:00
As we discussed above, you can construct your own sets with `[]`, where `[abc]` matches "a", "b", or "c" and `[^abc]` matches any character except "a", "b", or "c".
2023-03-09 11:02:03 +08:00
Apart from `^` there are two other characters that have special meaning inside of `[]:`
2021-04-21 21:43:19 +08:00
2023-04-10 23:22:08 +08:00
- `-` defines a range, e.g., `[a-z]` matches any lower case letter and `[0-9]` matches any number.
2022-11-10 04:47:46 +08:00
- `\` escapes special characters, so `[\^\-\]]` matches `^`, `-`, or `]`.
2021-04-21 21:43:19 +08:00
2022-10-06 22:05:13 +08:00
Here are few examples:
2022-01-04 05:25:03 +08:00
```{r}
2022-11-04 21:21:06 +08:00
x <- "abcd ABCD 12345 -!@#%."
str_view(x, "[abc]+")
str_view(x, "[a-z]+")
str_view(x, "[^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-06 05:55:47 +08:00
str_view("a-b-c", "[a-c]")
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-10-06 22:05:13 +08:00
Some character classes 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.
2023-03-09 11:02:03 +08:00
There are three other particularly useful pairs[^regexps-7]:
2022-10-06 22:05:13 +08:00
2023-03-09 11:02:03 +08:00
[^regexps-7]: 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"`.
2021-04-21 21:43:19 +08:00
2022-11-10 04:47:46 +08:00
- `\d` matches any digit;\
`\D` matches anything that isn't a digit.
2023-04-10 23:22:08 +08:00
- `\s` matches any whitespace (e.g., space, tab, newline);\
2022-11-10 04:47:46 +08:00
`\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
2022-10-06 22:05:13 +08:00
The following code demonstrates the six shortcuts with a selection of letters, numbers, and punctuation characters.
2021-04-21 21:43:19 +08:00
```{r}
2022-11-04 21:21:06 +08:00
x <- "abcd ABCD 12345 -!@#%."
str_view(x, "\\d+")
str_view(x, "\\D+")
str_view(x, "\\s+")
str_view(x, "\\S+")
2023-02-28 06:42:29 +08:00
str_view(x, "\\w+")
str_view(x, "\\W+")
2021-04-21 21:43:19 +08:00
```
2022-10-06 05:55:47 +08:00
### Quantifiers {#sec-quantifiers}
2021-04-21 21:43:19 +08:00
2022-11-04 21:21:06 +08:00
**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-10-06 22:05:13 +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 item of whitespace.
2022-11-04 21:21:06 +08:00
You can also specify the number of matches precisely with `{}`:
2021-04-21 21:43:19 +08:00
2022-10-06 22:05:13 +08:00
- `{n}` matches exactly n times.
- `{n,}` matches at least n times.
- `{n,m}` matches between n and m times.
2022-10-05 06:34:27 +08:00
### Operator precedence and parentheses
2022-01-05 07:58:02 +08:00
2022-01-18 12:49:41 +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?
2023-05-21 12:07:34 +08:00
Does it match the complete string a or the complete string b, or does it match a string starting with a or a string ending with b?
2022-01-12 16:08:01 +08:00
2022-11-04 21:21:06 +08:00
The answer to these questions is determined by operator precedence, similar to the PEMDAS or BEDMAS rules you might have learned in school.
2022-10-06 22:05:13 +08:00
You know that `a + b * c` is equivalent to `a + (b * c)` not `(a + b) * c` because `*` has higher precedence and `+` has lower precedence: you compute `*` before `+`.
2022-11-10 04:47:46 +08:00
2022-11-04 21:21:06 +08:00
Similarly, regular expressions have their own precedence rules: quantifiers have high precedence and alternation has low precedence which means that `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.
2022-11-04 21:21:06 +08:00
But 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
2022-10-05 06:34:27 +08:00
### Grouping and capturing
2023-01-23 22:35:09 +08:00
As well as overriding operator precedence, parentheses have another important effect: they create **capturing groups** that allow you to use sub-components of the match.
2022-10-06 22:05:13 +08:00
2022-11-04 21:21:06 +08:00
The first way to use a capturing group is to refer back to it within a match with **back reference**: `\1` refers to the match contained in the first parenthesis, `\2` in the second parenthesis, and so on.
2022-10-05 06:34:27 +08:00
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}
2022-11-04 21:21:06 +08:00
str_view(words, "^(..).*\\1$")
2022-10-05 06:34:27 +08:00
```
2022-11-04 21:21:06 +08:00
You can also use back references in `str_replace()`.
2022-10-06 22:05:13 +08:00
For example, this code switches the order of the second and third words in `sentences`:
2022-10-05 06:34:27 +08:00
```{r}
sentences |>
str_replace("(\\w+) (\\w+) (\\w+)", "\\1 \\3 \\2") |>
2022-10-06 22:05:13 +08:00
str_view()
2022-10-05 06:34:27 +08:00
```
2023-03-17 23:30:32 +08:00
If you want to extract the matches for each group you can use `str_match()`.
2023-03-09 11:02:03 +08:00
But `str_match()` returns a matrix, so it's not particularly easy to work with[^regexps-8]:
2022-10-06 22:05:13 +08:00
2023-03-09 11:02:03 +08:00
[^regexps-8]: Mostly because we never discuss matrices in this book!
2022-10-05 06:34:27 +08:00
```{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")
```
2022-11-04 21:21:06 +08:00
But then you've basically recreated your own version of `separate_wider_regex()`.
2022-11-06 01:06:02 +08:00
Indeed, behind the scenes, `separate_wider_regex()` converts your vector of patterns to a single regex that uses grouping to capture the named components.
2022-10-05 06:34:27 +08:00
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")
2022-11-04 21:21:06 +08:00
str_match(x, "gr(e|a)y")
str_match(x, "gr(?:e|a)y")
2022-10-05 06:34:27 +08:00
```
2021-04-21 21:43:19 +08:00
### Exercises
2022-10-06 22:05:13 +08:00
1. How would you match the literal string `"'\`? How about `"$^$"`?
2022-01-04 05:25:03 +08:00
2022-10-06 22:05:13 +08:00
2. Explain why each of these patterns don't match a `\`: `"\"`, `"\\"`, `"\\\"`.
2022-10-06 05:55:47 +08:00
2022-10-06 22:05:13 +08:00
3. Given the corpus of common words in `stringr::words`, create regular expressions that find all words that:
2022-01-04 05:25:03 +08:00
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.
2022-11-07 22:32:57 +08:00
f. Contain a vowel-consonant pair.
g. Contain at least two vowel-consonant pairs in a row.
2022-10-06 22:05:13 +08:00
h. Only consist of repeated vowel-consonant pairs.
2021-04-21 21:43:19 +08:00
2023-02-28 06:42:29 +08:00
4. Create 11 regular expressions that match the British or American spellings for each of the following words: airplane/aeroplane, aluminum/aluminium, analog/analogue, ass/arse, center/centre, defense/defence, donut/doughnut, gray/grey, modeling/modelling, skeptic/sceptic, summarize/summarise.
2022-10-05 06:34:27 +08:00
Try and make the shortest possible regex!
2022-01-06 12:49:31 +08:00
2022-11-07 22:32:57 +08:00
5. Switch the first and last letters in `words`.
Which of those strings are still `words`?
2022-01-04 05:25:03 +08:00
2022-10-06 22:05:13 +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-06 05:55:47 +08:00
e. `\..\..\..`
f. `(.)\1\1`
g. `"(..)\\1"`
2021-04-21 21:43:19 +08:00
2022-10-06 22:05:13 +08:00
7. Solve the beginner regexp crosswords at <https://regexcrossword.com/challenges/beginner>.
2022-10-05 06:34:27 +08:00
## Pattern control
2022-11-07 23:50:57 +08:00
It's possible to exercise extra control over the details of the match by using a pattern object instead of just a string.
2023-03-17 23:30:32 +08:00
This allows you to control the so called regex flags and match various types of fixed strings, as described below.
2022-10-05 06:34:27 +08:00
2022-10-06 22:05:13 +08:00
### Regex flags {#sec-flags}
2022-10-05 06:34:27 +08:00
2023-01-23 22:35:09 +08:00
There are a number of settings that can be used to control the details of the regexp.
2022-11-10 04:47:46 +08:00
These settings are often called **flags** in other programming languages.
2022-10-06 22:05:13 +08:00
In stringr, you can use these by wrapping the pattern in a call to `regex()`.
2022-10-05 06:34:27 +08:00
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))
```
2022-11-10 04:47:46 +08:00
If you're doing a lot of work with multiline strings (i.e. strings that contain `\n`), `dotall`and `multiline` may also be useful:
2022-10-05 06:34:27 +08:00
2022-11-06 01:06:02 +08:00
- `dotall = TRUE` lets `.` match everything, including `\n`:
2022-10-05 06:34:27 +08:00
2022-11-06 01:06:02 +08:00
```{r}
x <- "Line 1\nLine 2\nLine 3"
str_view(x, ".Line")
str_view(x, regex(".Line", dotall = TRUE))
```
2022-10-05 06:34:27 +08:00
2022-11-06 01:06:02 +08:00
- `multiline = TRUE` makes `^` and `$` 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))
```
2022-10-05 06:34:27 +08:00
2022-11-06 01:06:02 +08:00
Finally, if you're writing a complicated regular expression and you're worried you might not understand it in the future, you might try `comments = TRUE`.
It tweaks the pattern language to ignore spaces and new lines, as well as everything after `#`.
2023-03-09 11:02:03 +08:00
This allows you to use comments and whitespace to make complex regular expressions more understandable[^regexps-9], as in the following example:
2022-10-06 22:05:13 +08:00
2023-03-09 11:02:03 +08:00
[^regexps-9]: `comments = TRUE` is particularly effective in combination with a raw string, as we use here.
2022-10-05 06:34:27 +08:00
```{r}
2022-10-06 22:05:13 +08:00
phone <- regex(
r"(
\(? # optional opening parens
(\d{3}) # area code
2023-02-28 06:42:29 +08:00
[)\-]? # optional closing parens or dash
\ ? # optional space
2022-10-06 22:05:13 +08:00
(\d{3}) # another three numbers
[\ -]? # optional space or dash
2023-02-28 06:42:29 +08:00
(\d{4}) # four more numbers
2022-10-06 22:05:13 +08:00
)",
comments = TRUE
)
2022-10-05 06:34:27 +08:00
2023-02-28 06:42:29 +08:00
str_extract(c("514-791-8141", "(123) 456 7890", "123456"), phone)
2022-10-05 06:34:27 +08:00
```
2023-02-28 06:42:29 +08:00
If you're using comments and want to match a space, newline, or `#`, you'll need to escape it with `\`.
2021-04-21 21:43:19 +08:00
2022-10-06 05:55:47 +08:00
### Fixed matches
You can opt-out of the regular expression rules by using `fixed()`:
```{r}
str_view(c("", "a", "."), fixed("."))
```
2022-10-06 22:05:13 +08:00
`fixed()` also gives you the ability to ignore case:
2022-10-06 05:55:47 +08:00
```{r}
2022-10-06 22:05:13 +08:00
str_view("x X", "X")
str_view("x X", fixed("X", ignore_case = TRUE))
2022-10-06 05:55:47 +08:00
```
2022-11-07 22:32:57 +08:00
If you're working with non-English text, you will probably want `coll()` instead of `fixed()`, as it implements the full rules for capitalization as used by the `locale` you specify.
2022-11-06 01:06:02 +08:00
See @sec-other-languages for more details on locales.
2022-10-06 05:55:47 +08:00
```{r}
str_view("i İ ı I", fixed("İ", ignore_case = TRUE))
str_view("i İ ı I", coll("İ", ignore_case = TRUE, locale = "tr"))
```
2022-01-12 16:08:01 +08:00
## Practice
2022-11-10 04:47:46 +08:00
To put these ideas into practice we'll solve a few semi-authentic problems next.
We'll discuss three general techniques:
2023-01-23 22:35:09 +08:00
1. checking your work by creating simple positive and negative controls
2022-11-10 04:47:46 +08:00
2. combining regular expressions with Boolean algebra
3. creating complex patterns using string manipulation
2022-01-17 10:41:16 +08:00
### 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-11-07 22:32:57 +08:00
Because that pattern also matches sentences starting with words like `They` or `These`.
2023-04-17 20:07:22 +08:00
We need to make sure that the "e" is the last letter in the word, which we can do by 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.
2022-11-10 04:47:46 +08:00
A good technique is to create a few positive and negative matches and use them to test that your 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-11-07 22:32:57 +08:00
It's typically much easier to come up with good positive examples than negative examples, because it takes a while before you're good enough with regular expressions to predict where your weaknesses are.
Nevertheless, they're 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.
2022-01-12 16:08:01 +08:00
2022-05-14 04:46:49 +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-11-07 22:32:57 +08:00
But you can make this problem a bit easier by flipping the problem around.
2022-01-17 10:41:16 +08:00
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-11-06 01:06:02 +08:00
str_view(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-11-06 01:06:02 +08:00
str_view(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-11-10 04:47:46 +08:00
It's much simpler to combine five calls to `str_detect()`:
2022-01-17 10:41:16 +08:00
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-11-06 01:06:02 +08:00
But as the number of colors grows, it would quickly get tedious to construct this pattern by hand.
Wouldn't it be nice if we could store the colors in a vector?
2022-01-17 10:41:16 +08:00
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!
2022-09-01 19:43:57 +08:00
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.
2022-11-06 01:06:02 +08:00
One place we could start from is the list of built-in colors that R can use for plots:
2022-01-17 10:41:16 +08:00
```{r}
2022-10-06 22:05:13 +08:00
str_view(colors())
2022-01-12 16:08:01 +08:00
```
2022-11-07 22:32:57 +08:00
But lets first eliminate 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")]
2022-10-06 22:05:13 +08:00
str_view(cols)
2022-01-17 10:41:16 +08:00
```
2022-01-12 16:08:01 +08:00
2022-11-07 22:32:57 +08:00
Then we can turn this into one giant pattern.
We won't show the pattern here because it's huge, but you can see it working:
2022-01-17 10:41:16 +08:00
```{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-11-10 04:47:46 +08:00
In this example, `cols` only contains numbers and letters so you don't need to worry about metacharacters.
2023-01-23 22:35:09 +08:00
But in general, whenever you create patterns from existing strings it's wise to run them through `str_escape()` to ensure they match literally.
2022-01-17 10:41:16 +08:00
### Exercises
2022-11-04 21:21:06 +08:00
1. For each of the following challenges, try solving it by using both a single regular expression, and a combination of multiple `str_detect()` calls.
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?
2. Construct patterns to find evidence for and against the rule "i before e except after c"?
2022-10-06 22:05:13 +08:00
2022-11-04 21:21:06 +08:00
3. `colors()` contains a number of modifiers like "lightgray" and "darkblue".
2022-10-06 22:05:13 +08:00
How could you automatically identify these modifiers?
2022-11-06 01:06:02 +08:00
(Think about how you might detect and then removed the colors that are modified).
2022-10-06 22:05:13 +08:00
2022-11-04 21:21:06 +08:00
4. Create a regular expression that finds any base R dataset.
2022-10-06 22:05:13 +08:00
You can get a list of these datasets via a special use of the `data()` function: `data(package = "datasets")$results[, "Item"]`.
2022-11-07 22:32:57 +08:00
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 strip those off.
2022-01-04 05:25:03 +08:00
2022-11-07 22:32:57 +08:00
## Regular expressions in other places
2022-01-18 12:49:41 +08:00
2022-11-10 04:47:46 +08:00
Just like in the stringr and tidyr functions, there are many other places in R where you can use regular expressions.
2022-11-07 22:32:57 +08:00
The following sections describe some other useful functions in the wider tidyverse and base R.
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-11-07 22:32:57 +08:00
There are three other particularly useful places where you might want to use a regular expressions
2022-10-04 05:32:07 +08:00
2022-11-07 22:32:57 +08:00
- `matches(pattern)` will select all variables whose name matches the supplied pattern.
2023-04-10 23:22:08 +08:00
It's a "tidyselect" function that you can use anywhere in any tidyverse function that selects variables (e.g., `select()`, `rename_with()` and `across()`).
2022-10-04 05:32:07 +08:00
2023-01-23 22:35:09 +08:00
- `pivot_longer()'s` `names_pattern` argument takes a vector of regular expressions, just like `separate_wider_regex()`.
2022-11-07 22:32:57 +08:00
It's useful when extracting data out of variable names with a complex structure
2022-10-04 05:32:07 +08:00
2023-01-23 22:35:09 +08:00
- The `delim` argument in `separate_longer_delim()` and `separate_wider_delim()` usually matches a fixed string, but you can use `regex()` to make it match a pattern.
2022-11-07 22:32:57 +08:00
This is useful, for example, if you want to match a comma that is optionally followed by a space, i.e. `regex(", ?")`.
2022-10-04 05:32:07 +08:00
2022-11-07 22:32:57 +08:00
### Base R
2022-10-04 05:32:07 +08:00
2022-11-07 22:32:57 +08:00
`apropos(pattern)` searches all objects available from the global environment that match the given pattern.
This is useful if you can't quite remember the name of a function:
2022-10-04 05:32:07 +08:00
2022-10-06 22:05:13 +08:00
```{r}
apropos("replace")
```
2022-10-04 05:32:07 +08:00
2022-11-11 22:00:44 +08:00
`list.files(path, pattern)` lists all files in `path` that match a regular expression `pattern`.
2022-10-06 22:05:13 +08:00
For example, you can find all the R Markdown files in the current directory with:
2022-10-04 05:32:07 +08:00
2022-10-06 22:05:13 +08:00
```{r}
2022-11-11 22:00:44 +08:00
head(list.files(pattern = "\\.Rmd$"))
2022-10-06 22:05:13 +08:00
```
2022-10-04 05:32:07 +08:00
2022-11-07 22:32:57 +08:00
It's worth noting that the pattern language used by base R is very slightly different to that used by stringr.
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 use either the [TRE engine](https://github.com/laurikari/tre) or the [PCRE engine](https://www.pcre.org), depending on whether or not you've set `perl = TRUE`.
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.
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.
2022-10-05 06:34:27 +08:00
## Summary
2022-11-10 04:47:46 +08:00
With every punctuation character potentially overloaded with meaning, regular expressions are one of the most compact languages out there.
They're 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.
2022-11-07 22:32:57 +08:00
In this chapter, you've 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.
2022-11-10 04:47:46 +08:00
And there are plenty of resources to learn more.
2022-10-21 22:14:49 +08:00
2022-11-07 22:32:57 +08:00
A good place to start is `vignette("regular-expressions", package = "stringr")`: it documents the full set of syntax supported by stringr.
2022-10-05 06:34:27 +08:00
Another useful reference is [https://www.regular-expressions.info/](https://www.regular-expressions.info/tutorial.html).
2022-11-07 22:32:57 +08:00
It's not R specific, but you can use it to learn about the most advanced features of regexes and how they work under the hood.
2022-11-10 04:47:46 +08:00
2023-02-28 06:42:29 +08:00
It's also good to know that stringr is implemented on top of the stringi package by Marek Gagolewski.
2022-11-07 22:32:57 +08:00
If you're struggling to find a function that does what you need in stringr, don't be afraid to look in stringi.
You'll find stringi very easy to pick up because it follows many of the the same conventions as stringr.
2022-10-21 22:14:49 +08:00
In the next chapter, we'll talk about a data structure closely related to strings: factors.
2022-11-10 04:47:46 +08:00
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.