Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove all characters between two other characters (keeping the other characters)

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'

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading