1. Learn
  2. /
  3. Courses
  4. /
  5. String Manipulation with stringr in R

Exercise

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.

Instructions 1/4

undefined XP
  • 1

    Match any character followed by a t.

  • 2

    Match a t followed by any character. Notice how the final t in cat and coat don't match, that's because there is no character after the t to match to ANY_CHAR.

  • 3

    Match any two characters. Notice the first two characters are matched. Regular expressions are lazy and will take the first match they find.

  • 4

    Match a string that is exactly three characters.