i’m trying to replace a part of a string which is matched like in the following example:
str1 <- "abc sdak+ 123+"
I would like to replace all + that come after 3 numbers, but not in the case when a + is coming after characters. I tried like this, but this replaces the whole matched string, when I only want to replace the + with a -
gsub("[0-9]{3}\\+", "-", str1)
The desired outcome should be:
"abc sdak+ 123-"
>Solution :
We could capture the 3 digits as a group ((...)) and the +, replace with the backreference (\\1) of the captured group and the -. Just to make sure that there is no digits before the 3 digits, use either word boundary (\\b) or a space (\\s)
gsub("\\b(\\d{3})\\+", "\\1-", str1)
-output
[1] "abc sdak+ 123-"