library(stringr)
<- c("I have a cat", x "Tom has a dog", "There are many animals on the farm")
Alternation: Match Any One of Specified Patterns
|
denotes alternation, and allows you to match one of the two or more specified patterns
eg. 1. animal|cat|dog
matches “animal”, “cat”, and “dog” in a string.
str_view_all(x, "animal|cat|dog")
Output:
[1] │ I have a <cat>
[2] │ Tom has a <dog>
[3] │ There are many <animal>s on the farm
str_extract(x, "animal|cat|dog")
Output:
[1] "cat" "dog" "animal"
eg. 2. \\d{3,7}
matches any 3 to 7 consecutive digits, and [:alpha:]{4,6}
matches any 4 to 6 alphabetical letters. \\d{3,7}|[:alpha:]{4,6}
makes a match with both patterns.
<- c("233-abcd-12345", "124-ABCDEF-79265") a <- "\\d{3,7}|[:alpha:]{4,6}" p
str_view_all(a, p)
Output:
[1] │ <233>-<abcd>-<12345>
[2] │ <124>-<ABCDEF>-<79265>
str_extract_all(a, p, simplify = T)
Output:
[,1] [,2] [,3]
[1,] "233" "abcd" "12345"
[2,] "124" "ABCDEF" "79265"