wen wen - 4 years ago 98
R Question

How to remove strings with exceptions in R?

I have a string. I want to (a) keep "/" in fractions, (b) insert whitespace around "/" that are between words, and (c) remove all other "/".

s = "/// // / 1/2 111/222 a/b abc/abc a / b / // ///"


The result should be as follows.

s = "1/2 111/222 a b abc abc a b"


I have tried a few things. I cannot make everything right.

Answer Source

I'm not a regex expert, but this appears to work on your example.

s = "/// // / 1/2 111/222 a/b  abc/abc a / b /  // ///"

i <- gsub("/{2,}|/\\s", "", s)
i <- trimws(gsub("([[:alpha:]]{1,})(/)([[:alpha:]]{1,})", "\\1 \\3", i))
i <- gsub("\\s{2,}", " ", i)

identical(i, "1/2 111/222 a b abc abc a b")

[1] TRUE
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download