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

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"

Example 2: Using str_extract() Function of stringr Package to Return Regular Expression Match

install.packages("stringr")        # Install & load stringr
library("stringr")
str_extract(x, expr)               # Extracting regular expression macth
# [1] "500"

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top