I know this question has been asked multiple times in different ways, but I can't find a solution where I would replace the text between some "borders" while keeping the borders.
input <- "this is my 'example'"
change <- "test"
And now I want to replace everything between teh single quotes with the value in change
.
Expected output would be "this is my 'test'
I tried different variants of:
stringr::str_replace(input, "['].*", change)
But it doesn't work. Eg the one above gives "this is my test"
, so it doesn't have the single quotes anymore.
Any ideas?
You can use
stringr::str_replace_all(input, "'[^']*'", paste0("'", change, "'"))
gsub("'[^']*'", paste0("'", change, "'"), input)
Or, you may also capture the apostophes and then use backreferences, but that would look uglier (cf. gsub("(')[^']*(')", paste0("\\1",change,"\\2"), input)
).
See the R demo online:
input <- "this is my 'example'"
change <- "test"
stringr::str_replace_all(input, "'[^']*'", paste0("'", change, "'"))
gsub("'[^']*'", paste0("'", change, "'"), input)
Output:
[1] "this is my 'test'"
[1] "this is my 'test'"
Note : if your change
variable contains a backslash, it must be doubled to avoid issues:
stringr::str_replace_all(input, "'[^']*'", paste0("'", gsub("\\", "\\\\", change, fixed=TRUE), "'"))
gsub("'[^']*'", paste0("'", gsub("\\", "\\\\", change, fixed=TRUE), "'"), input)
Using sub()
we can try:
input <- "this is my 'example'"
change <- "test"
output <- sub("'.*?'", paste0("'", change, "'"), input)
output
[1] "this is my 'test'"
And this way?
input <- "this is my 'example'"
change <- "test"
stringr::str_replace(input, "(?<=').*?(?=')", change)
(?<=') ← look the character before is a ' without catching it.
. ← catch any characters but as less as possible. To covert a case like "this is my 'example' did you see 'it' "
(?=') ← look the character following is a ' without catching it.
↓ Tested here ↓
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.