Question

I have a string like below.

testSampe <- "Old:windows\r\nNew:linux\r\n"

I want to erase the string between ":" an "\".

Like this "Old\r\nNew\r\n".

How can I construct the regex for this?

I tried to gsub function with regex ":.*\\\\", It doesn't work.

 gsub(":.*\\\\", "\\\\r", testSampe)
Was it helpful?

Solution

> testSampe <- "Old:windows\r\nNew:linux\r\n"
> gsub(":[^\r\n]*", "", testSampe)
[1] "Old\r\nNew\r\n"

OTHER TIPS

You have a choice of a few different regular expressions that will match. See falsetru's answer or use:

rx <- ":[[:alnum:]]*(?=\\r)"

As a more readable alternative to gsub, use str_replace_all in the stringr package.

library(stringr)
str_replace_all(testSampe, perl(rx), "")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top