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.

library(stringr)
x <- c("I have a cat", "Tom has a dog", "There are many animals on the farm")
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.

a <- c("233-abcd-12345", "124-ABCDEF-79265")p <- "\\d{3,7}|[:alpha:]{4,6}"
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"