I\'m looking for a way to use the find and replace function in R to replace the entire value of a string, rather than just the matching part of the string. I have a dataset with
You can use gsub
as follows:
gsub(".*experiences.*", "exp", string, perl=TRUE)
# As @rawr notes, set perl=TRUE for improved efficiency
This regex matches strings that have any characters 0 or more times (i.e. .*
) followed by "experiences", followed by any characters 0 or more times.
In this case, you are still replacing the entire match with "exp" but by using regex, you expand the definition of the match (from "experience" to ".*experience.*") to achieve the desired substitution.