Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
regex in R yt
##%######################################################%##
# #
#### Regex in R - Your Turn ####
# #
##%######################################################%##
# Match the following regular expressions against the test vector below using `str_detect`.
## Can you explain the matches?
# Regular expressions
# 1. ^dog
# 2. ^[a-z]+$
# 3. \\d
test_vector <- c("Those dogs are small.","dogs and cats",
"34","(34)","rat","watchdog","placemat",
"BABY","2011_April","mice")
# load packages -----------------------------------------------------------
library(stringr)
# create text string ------------------------------------------------------
test_vector <- c("Those dogs are small.","dogs and cats",
"34","(34)","rat","watchdog","placemat",
"BABY","2011_April","mice")
# evaluate if each element contains a match -------------------------------
# match the literal string dog
str_detect(test_vector,"^dog") # second element contains match
# match lowercase
str_detect(test_vector,"^[a-z]+$") # elements 5,6,7, and 10 matched
# match numbers
str_detect(test_vector,"\\d") # elements 3,4, and 9 matched
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment