r check if string contains special characters

Jill Sellum picture Jill Sellum · Apr 29, 2016 · Viewed 8k times · Source

I am checking if a string contains any special characters. This is what I have, and its not working,

    if(grepl('^\\[:punct:]', val))

So if anybody can tell me what I am missing, that will be helpful.

Special characters

        ~ ` ! @# $ % ^ & * | : ; , ." |

Answer

octothorpe_not_hashtag picture octothorpe_not_hashtag · Apr 27, 2017

As @thelatemail pointed out in the comments you can use:

grepl('[^[:punct:]]', val)

which will result in TRUE or FALSE for each value in your vector. You can add sum() to the beginning of the statement to get the total number of these cases.

You can also use:

grepl('[^[:alnum:]]', val)

which will check for any value that is not a letter or a number.