Regular Expression
RegEx Functions
Action
Function
Search for a substring within a string
grep(substring/value, string)
Replace a single value within a string
sub(pattern, replacement, string)
Replace all instances within a string
gsub(pattern, replacement, string)
Find matches for exact string
grepl(pattern, string)
Inputs:
#Search for substring in a string
y <- c("carrot", "apple", "banana", "carrot")
grep("carrot", y)
#Replace a single value within a string
sub("r”, “R”, y)
#Replace all instances within a string
gsub(“r”, “R”, y)
#Find matches of exact strings
grepl("car", y)
Outputs:
#Search for value in a string
1 4
#Returns the position of the value searched for
#Replace the first instance of a single value within a string
"caRrot" "apple" "banana" "caRrot"
#Replace all instances within a string
"caRRot" "apple" "banana" "caRRot"
#Find matches of exact strings
TRUE FALSE FALSE TRUE
Resources
DataCamp: Regular Expression
Last updated