Docsity

Regular Expressions (regex) in R with stringr Package, Lecture notes of Data Analysis & Statistical Methods

Partial preview of the text

Download Regular Expressions (regex) in R with stringr Package and more Lecture notes Data Analysis & Statistical Methods in PDF only on Docsity!

Text Data and RegexText Data and Regex

Statistical Computing &Statistical Computing &

ProgrammingProgramming

Shawn SantoShawn Santo

Supplementary materials

Companion videos

Introduction to stringr Escaping metacharacters More metacharacters and their functionality Quantifies

Additional resources

stringr vignette stringr cheat sheet regex guide

Why stringr?

Part of tidyverse

Fast and consistent manipulation of string data

Readable and consistent syntax

If you master stringr, you know stringi - http://www.gagolewski.com/software/stringi/

Usage

All functions in stringr start with str_ and take a vector of strings as the first argument.

Most stringr functions work with regular expressions.

Seven main verbs to work with strings.

Function Description str_detect() Detect the presence or absence of a pattern in a string. str_count() Count the number of patterns. str_locate() Locate the first position of a pattern and return a matrix with start and end. str_extract() Extracts text corresponding to the first match. str_match() Extracts capture groups formed by () from the first match. str_split() Splits string into pieces and returns a list of character vectors. str_replace() Replaces the first matched pattern and returns a character vector.

Each have leading arguments string and pattern; all functions are vectorised over arguments string and pattern.

Function assistance and visuals: stringr cheat sheet 5 / 29

How many of t, th, and the exist?

#> [1] 10 8 2

Do these patterns exist?

#> [1] TRUE TRUE TRUE

Simple cases

A regular expression, regex or regexp, is a sequence of characters that define a search pattern.

library (tidyverse)

twister <- "thirty-three thieves thought they thrilled the throne Thursday"

How many occurrences of t exist?

str_count(string = twister, pattern = "t")

#> [1] 10

str_count(twister, c("t", "th", "the")) str_detect(twister, c("t", "th", "the"

Separate our long string at each space.

twister_split <- str_split(twister, " ") %>% unlist() twister_split

#> [1] "thirty-three" "thieves" "thought" "they" #> [5] "thrilled" "the" "throne" "Thursday"

Do these patterns exist?

str_detect(twister_split, c("tho", "the"))

#> [1] FALSE FALSE TRUE TRUE FALSE TRUE FALSE FALSE

Replace certain occurrences.

str_replace(twister_split, c("tho", "the"), replacement = c("bro", "Wil"))

#> [1] "thirty-three" "thieves" "brought" "Wily" #> [5] "thrilled" "Wil" "throne" "Thursday"

How do we match an actual .?

You need to use an escape character to tell the regex you want exact matching.

Regexs use a \ as an escape character. So why doesn't this work?

str_view_all("show.me.the.dots...", ".")

#> Error: '.' is an unrecognized escape in character string starting ""."

R escape characters

There are some special characters in R that cannot be directly coded in a string. An escape character is a character which results in an alternative interpretation of the following character(s). These vary from language to language but for most string implementations \ is the escape character which is modified by a single subsequent character.

Some common examples:

Literal Character ' single quote " double quote \ backslash \n new line \r carriage return \t tab \b backspace \f form feed

Examples

print("hello\world")

#> Error: '\w' is an unrecognized escape in character string starting ""hello\w"

cat("hello\world")

#> Error: '\w' is an unrecognized escape in character string starting ""hello\w"

print("hello\tworld")

#> [1] "hello\tworld"

cat("hello\bworld")

#> [1] hellworld

print("hello"world")

#> [1] "hello"world"

print("hello\tworld")

#> [1] "hello\tworld"

print("hello\nworld")

#> [1] "hello\nworld"

print("hello\world")

#> [1] "hello\world"

cat("hello"world")

#> hello"world

cat("hello\tworld")

#> hello world

cat("hello\nworld")

#> hello #> world

cat("hello\world")

#> hello\world

Regex metacharacters

. ^ $ * +? { } [ ] \ | ( )

Allow for more advanced forms of pattern matching.

As we saw with ., these cannot be matched directly. Thus, if you want to match the literal? you will need to use \?.

What do you need to match a literal \ in regex pattern matching?

str_view_all("find the \ in this string", "\\")

find the \ in this string

Regex anchors

Sometimes we want to specify that our pattern occurs at a particular location in a string, we indicate this using anchor metacharacters.

Regex Anchor ^ or \A Start of string $ or \Z End of string

Character classes

Special patterns exist to match more than one class.

Meta Character Class Description

. Any character except new line (\n) \s [:space:] White space (space, tab, newline) \S Not white space \d [:digit:] Digit (0-9) \D Not digit \w Word (A-Z, a-z, 0-9, or _) \W Not word [:punct:] Punctuation

Character class overview