Matching any character
In a regular expression you can use a wildcard to match a single character, no matter what the character is. In rebus
it is specified with ANY_CHAR
. Try typing ANY_CHAR
in the console. You should see that in the regular expression language this is specified by a dot, .
.
For example, "c" %R% ANY_CHAR %R% "t"
will look for patterns like "c_t" where the blank can be any character. Consider the strings: "cat"
, "coat"
, "scotland"
and "tic toc"
. Where would the matches to "c" %R% ANY_CHAR %R% "t"
be?
Test your intuition by running:
str_view(c("cat", "coat", "scotland", "tic toc"),
pattern = "c" %R% ANY_CHAR %R% "t")
Notice that ANY_CHAR
will match a space character (c t
in tic toc
). It will also match numbers or punctuation symbols, but ANY_CHAR
will only ever match one character, which is why we get no match in coat
.
This exercise is part of the course
String Manipulation with stringr in R
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Match two characters, where the second is a "t"
str_view(x, pattern = ___)