To replace all occurrences of a substring in a string using regular expression in R, you can use the gsub
function.
In this example,
str
.gsub
function to replace all occurrences of "Hello" with "Hi".str <- 'Hello World Hello'
new_str <- gsub('Hello', 'Hi', str)
print(new_str)
Hi World Hi
In this example,
str
.gsub
function to replace all occurrences of digits (\d) with 'Y'.str <- 'Hello123World789'
new_str <- gsub('[0-9]', 'Y', str)
print(new_str)
HelloYYYWorldYYY
In this tutorial, we learned How to Replace a Substring in a String using Regular Expression in R language with well detailed examples.