Make advanced patterns more readable
Alright, you already master creating patterns that match a list of names by collapsing them using the pipe |
as a separator. But collapsing is also useful to concatenate small, digestible parts of a pattern. Using glue_collapse()
and vector (with or without names, both is possible) as its only input, you can create very long and complicated patterns out of small pieces that are much easier to interpret.
The variable users
was exported from our database and is again available in the global scope. But in this exercise, we are not only interested in the usernames, but also the digit and the email address that follow.
This exercise is part of the course
Intermediate Regular Expressions in R
Exercise instructions
- Have a look at the contents of
users
again. - Where we expect our username, write a pattern that matches one or more alphabetical letters. Use square brackets
[]
to create this custom pattern. - Where we expect the number of logins for that user, write a pattern that matches one or more digits. Use the digit character class for this.
- As the email comes last in every line, write a simple pattern that matches one or more arbitrary characters.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Familiarize yourself with users by printing its contents
print(___)
advanced_pattern <- glue_collapse(c(
# Match one or more alphabetical letters
"username" = "^___",
": ",
# Match one or more digit
"logins" = "___",
", ",
# Match one or more arbitrary characters
"email" = "___$"
))
str_view(users, advanced_pattern)