My code takes a string and replaces all characters which are not:

  • English letters
  • Numbers
  • , / -

I have tested it and it seems to generally work well enough. But it may have some catastrophic bug in it and/or can be simplified.

x <- "dog/John is a cutting-edge pilot^¢„þ"
gsub("[^a-zA-Z0-9,-:space:]+", " ", x, perl = TRUE)
"dog/John is a cutting-edge pilot "

The :space: portion of the regex makes no sense, and probably does not do what you intend.

> x <- "abc:def."
> gsub("[^a-zA-Z0-9,-:space:]", " ", x, perl = TRUE)
[1] "abc:def."

Notice that the colon and period are still present after the substitution.

In fact, inside the character class, ,-: means "all characters with ASCII codes from 44 (the comma) up to 58 (the colon)".

A literal hyphen must be the first or the last character in a character class; otherwise, it is treated as a range (like A-Z).

If you want a character class for whitespace, use "\\s" or [:space:].

So, if you wanted to convert all consecutive strings of junk to a single space, preserving only letters, digits, commas, slashes, hyphens, and whitespace, you could write:

gsub("[^-,/a-zA-Z0-9[:space:]]+", " ", x, perl = TRUE)


gsub("[^-,/a-zA-Z0-9\\s]+", " ", x, perl = TRUE)
| improve this answer | |
  • \$\begingroup\$ Two things: 1. Last line of answer is missing closing bracket ] 2. In this answer, each unwanted character is separately converted to a blank. Applying this answer to the test string results in an answer with multiple blanks at the end. The OP had a + so that multiple consecutive unwanted characters would become a single blank. \$\endgroup\$ – G5W May 7 '17 at 15:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.