---
title: "Textual Data<br>Regular Expressions"
author: "Keith VanderLinden<br>Calvin University"
output:
  xaringan::moon_reader:
    nature:
      titleSlideClass: ["left", "top"]
      highlightLines: true
      ratio: "16:9"     
---

```{r child = "../../resources/scripts/slide-setup.Rmd"}
```

```{r packages, echo = FALSE, warning = FALSE, message = FALSE}
knitr::opts_chunk$set(eval = TRUE)
options(dplyr.print_max = 12)
library(tidyverse)
```

# Regular Expressions: Matches

```{r}
fruit <- c("apple", "banana.", "pear ")
```

.pull-left[
**Basic Matches**

```{r}
str_view(fruit, "an")
str_view(fruit, "a\\.")
```
]
.pull-right[
**Pattern Matches**

```{r}
str_view(fruit, "a.")
str_view(fruit, ".r\ ")
```
]

???
- We use `\.` as an *escape* for regex period and `\\` for a string slash. This is a double-escape of sorts.

---
# Regular Expressions: Anchors

```{r}
fruit <- c("apple", "banana", "pear.")
```

.pull-left[
**Begin String**

```{r}
str_view(fruit, "a")
str_view(fruit, "^a")
```
]
.pull-right[
**End String**

```{r}
str_view(fruit, "a")
str_view(fruit, "a$")
```
]

???

---
# Regular Expressions: Character Classes

```{r}
codes <- c("a1", "a 1", "12")
```

.pull-left[
**Digits &amp; White Space**

```{r}
str_view(codes, "\\d")
str_view(codes, "a\\s")
```
]
.pull-right[
**Characters**

```{r}
str_view(codes, "[a-z]")
str_view(codes, "[^a]\\d")
```
]

???
White space includes spaces, tables, & newlines.

---
# Regular Expressions: Repetition

```{r}
s <- "MDCCCLXXXVIII"
```

.pull-left[
```{r}
str_view(s, "DC?")
str_view(s, "DC+")
str_view(s, "D*")
```
]
.pull-right[
```{r}
str_view(s, "C{1}")
str_view(s, "C{2,}")
str_view(s, "[CD]{2,4}")
```
]

???
- 1888 is the longest year in Roman numerals: MDCCCLXXXVIII.
- Operators
    - `?`: 0 or 1 matches
    - `+`: 1 or more matches
    - `*`: 0 or more matches

---
# Summary

Regular expressions provide a language for specifying string patterns.

.footnote[See H. Wickam&rsquo;s Matching patterns with regular expressions: https://r4ds.had.co.nz/strings.html?q=regular#matching-patterns-with-regular-expressions]

???
- They are critical for text analysis.
- Refer back to the regex used in the NLP slides.