Extracting Match of Regular Expression in R (2 Examples)
In this article you’ll learn how to locate and return a regular expression match in R programming.
Example Data
x <- "AA A A 500 XYZ" # Our example string expr <- "[0-9]+" # Our regular expression |
x <- "AA A A 500 XYZ" # Our example string expr <- "[0-9]+" # Our regular expression
Example 1: Using regmatches() & regexpr() Functions of Base R to Return Regular Expression Match
regmatches(x, regexpr(expr, x)) # Extracting regular expression macth # [1] "500" |
regmatches(x, regexpr(expr, x)) # Extracting regular expression macth # [1] "500"
Example 2: Using str_extract() Function of stringr Package to Return Regular Expression Match
install.packages("stringr") # Install & load stringr library("stringr") |
install.packages("stringr") # Install & load stringr library("stringr")
str_extract(x, expr) # Extracting regular expression macth # [1] "500" |
str_extract(x, expr) # Extracting regular expression macth # [1] "500"