Home > Blockchain >  Remove all characters between two other characters (keeping the other characters)
Remove all characters between two other characters (keeping the other characters)

Time:11-23

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. E.g. the one above gives "this is my test", so it doesn't have the single quotes anymore.

Any ideas?

CodePudding user response:

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 ↓

ideone

CodePudding user response:

Using sub() we can try:

input <- "this is my 'example'"
change <- "test"
output <- sub("'.*?'", paste0("'", change, "'"), input)
output

[1] "this is my 'test'"

CodePudding user response:

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)
  • Related