Search and replace
The function str_replace()
is a general function to replace parts of a string. A common application is to replace something with an empty string - which is a simple way to remove unneeded parts from a string.
With capturing groups, str_replace()
gets even more interesting: They enable you to change the order of things. By adding so called "backreferences" to the replacement, str_replace()
will replace these references with the contents of the corresponding capturing group. For example: If you write \\1
, this will be replaced with the 1st capturing group.
In this exercise, you'll see the first use (remove a substring) and the second (reorder two parts of a string) side by side. In the scope, you'll find the variable top_10_lines
from the last exercise.
This exercise is part of the course
Intermediate Regular Expressions in R
Exercise instructions
- Remove
3D
from the end of each line intop_10_lines
by replacing it with an empty string. - Form a new sentence with the two capturing groups. Reorder them so they result in e.g.
"Karate Kid is on rank 1"
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Remove a space followed by "3D" at the end of the line
str_replace(
top_10_lines,
pattern = "___",
replacement = ___
)
# Use backreferences 2 and 1 to create a new sentence
str_replace(
top_10_lines,
pattern = "(\\d+)\\. (.*)",
replacement = "___ is at rank ___"
)