How to Use StrExtract() Function in R (DescTools Package)

StrExtract() function from the DescTools package in R is “used to extract a part of a string, defined as a regular expression”.

Syntax

StrExtract(x, pattern)

Parameters

  1. x: It is a character vector where matches are sought, or an object can be coerced by as.character to a character vector.
  2. pattern: It is a character string containing a regular expression (or character string for fixed = TRUE) to be matched in the given character vector.

Return value

It returns a character vector.

Example 1: R program of StrExtract() function

library(DescTools)

state <- "We are Venom"

StrExtract(state, "Venom")

Output

[1] "Venom"

    Example 2: Using regex in StrExtract() Function

    You can also use regular expressions to specify more complex patterns.

    library(DescTools)
    
    state <- "We are Venom"
    
    StrExtract(state, "\\bV\\w*m\\b")

    Output

    [1] "Venom"

    That’s it.

    Leave a Comment