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...

  1. Define a test vector that you can search with regular expressions:
    test_string <- c("012","345",";.","kdj","KSR" ,"
    ")
    
  2. Look for digits:
    grep("[[:digit:]]",test_string, value = TRUE)
    which will result in :
    [1] "012" "345"
    
  3. Look for punctuation:
    grep("[[:punct:]]",test_string, value = TRUE)
    which will have as a result
    [1] ";."
    
  4. Look for lowercase letters:
    grep("[[:lower:]]",test_string, value = TRUE)
    

    Which will select the following:

    [1] "kdj"
    
  5. Look for uppercase letters:
          grep("[[:upper:]]",test_string, value = TRUE)
    

    Which will select only upper cases:

         [1] "KSR"
    
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset