Capturing

String Manipulation with stringr in R

Charlotte Wickham

Assistant Professor at Oregon State University

Capturing

ANY_CHAR %R% "a"
<regex> .a
capture(ANY_CHAR) %R% "a"
<regex> (.)a
str_extract(c("Fat", "cat"), 
    pattern = ANY_CHAR %R% "a")
"Fa" "ca"
str_extract(c("Fat", "cat"), 
    pattern = capture(ANY_CHAR) %R% "a")
"Fa" "ca"
String Manipulation with stringr in R

str_match()

str_match(c("Fat", "cat"), 
    pattern = capture(ANY_CHAR) %R% "a")
     [,1] [,2]
[1,] "Fa" "F" 
[2,] "ca" "c"
String Manipulation with stringr in R

str_match()

pattern <- DOLLAR %R% 
             DGT %R% optional(DGT) %R% 
             DOT %R% 
             dgt(2)

str_view(c("$5.50", "$32.00"), pattern = pattern)

chap_4_1.013.png

String Manipulation with stringr in R

str_match()

pattern <- DOLLAR %R% 
             capture(DGT %R% optional(DGT)) %R% 
             DOT %R% 
             capture(dgt(2))

str_match(c("$5.50", "$32.00"), pattern = pattern)
     [,1]     [,2] [,3]
[1,] "$5.50"  "5"  "50"
[2,] "$32.00" "32" "00"
String Manipulation with stringr in R

Non-capturing groups

or("dog", "cat")
<regex> (?:dog|cat)

chap_4_1.021.png

String Manipulation with stringr in R

Non-capturing groups

or("dog", "cat")
<regex> (?:dog|cat)

chap_4_1.023.png

or("dog", "cat", capture = TRUE)
<regex> (dog|cat)
capture(or("dog", "cat"))
<regex> ((?:dog|cat))
String Manipulation with stringr in R

Let's practice!

String Manipulation with stringr in R

Preparing Video For Download...