Dealing with regular expressions
Regular expressions let you easily perform string manipulation with the help of just a handful of characters. In this recipe, we will look for digits, punctuation, and uppercase and lowercase in a vector of strings.
How to do it...
- Define a
test
vector that you can search with regular expressions:test_string <- c("012","345",";.","kdj","KSR" ,"\n")
- Look for digits:
grep("[[:digit:]]",test_string, value = TRUE) which will result in : [1] "012" "345"
- Look for punctuation:
grep("[[:punct:]]",test_string, value = TRUE) which will have as a result [1] ";."
- Look for lowercase letters:
grep("[[:lower:]]",test_string, value = TRUE)
Which will select the following:
[1] "kdj"
- Look for uppercase letters:
grep("[[:upper:]]",test_string, value = TRUE)
Which will select only upper cases:
[1] "KSR"