What is the gregexpr() function in R?

Overview

The gregexpr() function in R is used to return a substring matching the pattern passed to the function.

Syntax

gregexpr(pattern, text, ignore.case=FALSE, perl=FALSE,
	fixed=FALSE, useBytes=FALSE, extract=FALSE)

Parameters

The gregexpr() function takes the following parameter values:

  • pattern (required): This is the character string to be matched in the input character vector.
  • text (required): This is the character vector that has the desired character string to be sorted.
  • ignore.case (optional): This takes a boolean value TRUE or FALSE indicating whether the patch pattern matching (if TRUE) is case sensitive, or ignored during matching (if FALSE.)
  • perl (optional): This takes a boolean value TRUE or FALSE to indicate whether Perl-compatible regular expressions are being used or not.
  • fixed (optional): This takes a boolean value TRUE or FALSE to indicate whether the pattern is a string to be matched as is (if TRUE) or overrides all conflicting arguments (if FALSE).
  • useBytes (optional): This takes a boolean value TRUE or FALSE to indicate whether the matching is done byte-by-byte (if TRUE), rather than character-by-character (if FALSE).
  • extract (optional): This takes a boolean value TRUE or FALSE to indicate whether the matching substrings should be extracted and returned or not.

Code example

# creating a character vector
mypattern <- c("JBDSGKJKLJKGFSKLJH","FDLAKLGISRI")
# implementing the gregexpr() functiton
gregexpr("DSG", mypattern, useBytes = TRUE)

Code explanation

  • Line 2: We create a vector object mypattern containing the pattern to match.
  • Line 5: We implement the gregexpr() function and print the result to the console.

Free Resources