I have a string and I want to remove all non-alphanumeric symbols from and then put into a vector. So this:
"This is a string. In addition, this is a string!"
would become:
>stringVector1
"This","is","a","string","In","addition","this","is","a","string"
I've looked at grep()
but can't find an example that matches. Any suggestions?
A common solution to remove all non-alphanumeric characters from a String is with regular expressions. The idea is to use the regular expression [^A-Za-z0-9] to retain only alphanumeric characters in the string. You can also use [^\w] regular expression, which is equivalent to [^a-zA-Z_0-9] .
Answer : Use [^[:alnum:]] to remove ~! @#$%^&*(){}_+:"<>?,./;'[]-= and use [^a-zA-Z0-9] to remove also â í ü Â á ą ę ś ć in regex or regexpr functions.
To remove all non-alphanumeric characters from a string, call the replace() method, passing it a regular expression that matches all non-alphanumeric characters as the first parameter and an empty string as the second. The replace method returns a new string with all matches replaced.
Non-alphanumeric characters can be remove by using preg_replace() function. This function perform regular expression search and replace. The function preg_replace() searches for string specified by pattern and replaces pattern with replacement if found.
here is an example:
> str <- "This is a string. In addition, this is a string!" > str [1] "This is a string. In addition, this is a string!" > strsplit(gsub("[^[:alnum:] ]", "", str), " +")[[1]] [1] "This" "is" "a" "string" "In" "addition" "this" "is" "a" [10] "string"
Another approach to handle this question
library(stringr) text = c("This is a string. In addition, this is a string!") str_split(str_squish((str_replace_all(text, regex("\\W+"), " "))), " ") #[1] "This" "is" "a" "string" "In" "addition" "this" "is" "a" "string"
str_replace_all(text, regex("\\W+"), " ")
: find non-word character and replace " "
str_squish()
: reduces repeated whitespace inside a stringstr_split()
: split up a string into piecesIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With