This brief document discusses how to search in R for some exemplary regular expressions that we discussed in the lecture.

Loading packages (the tidyverse includes the `readr` and `stringr` packages that we are using here):

```{r}
library("tidyverse")
#install.packages("htmlwidgets")
```

Load the txt file into a character vector with `read_file`:

```{r}
sample_text <- read_file("data/sample_texts.txt")
```

Helpful functions are e.g. `str_view`, `str_view_all`, `str_extract`, `str_extract_all`. The `_all` variants process all matches in the string rather than only the first.

The view function allows to view keyword and/or regular expression matches in R similarly to in a text editor:

```{r}
str_view(sample_text, "@")
```

```{r}
str_view_all(sample_text, "@")
```

```{r}
str_view_all(sample_text, "a|e")
```

The extract function on the other hand allows to extract the matching characters. The following regular expression is one possible way to use the options we discussed this week to extract the times from the file (as the backslash is already used as an escape symbol in normal strings in R, we need to use a double backslash for regular expressions):

```{r}
# \d = a digit
# \d{1,2} = 1-2 digits, e.g. "1", "11", "23"
# [:.\\s-]? = optional set of characters (":","."," ","-")
str_extract(sample_text, "\\d{1,2}[:.\\s-]?\\d{0,2}")
```

```{r}
str_extract_all(sample_text, "\\d{1,2}[:.\\s-]?\\d{0,2}")
```

Other helpful functions are e.g. `str_detect` (particularly when all words are elements in a long character vector) and `str_count`. For a detailed discussion of strings and regular expressions in R with the `stringr` package, see http://r4ds.had.co.nz/strings.html and the vignette https://cran.r-project.org/web/packages/stringr/vignettes/regular-expressions.html.
