grepl in R: How to Use grepl() Function in R

We often come across a functionality where we want to check something by comparing it with patten. We use a regular expression to match certain character vectors in the string. Let’s see how to use regular expression in R.

grepl in R

The grepl() is a built-in function that searches for matches of a string or string vector. It returns TRUE if a string contains the pattern, otherwise FALSE. If the parameter is a string vector, it returns a logical vector (match or not for each vector element). It stands for “grep logical”.

To find a pattern in string or string vector, use the grepl() function. In their most basic form, regular expressions can be used to see whether a pattern exists inside a character string or a vector of character strings.


grepl(pattern, x, = FALSE, perl = FALSE,
      fixed = FALSE, useBytes = FALSE)


pattern: It is a regular expression or string for fixed=TRUE

x: It is a string, the character vector

perl: It is logical. Should Perl-compatible regexps be used? Has priority overextended.

fixed: It is logical. If the TRUE, the pattern is a string to be matched as is. Overrides all conflicting arguments

useBytes: It is logical. If TRUE, the matching is done byte-by-byte rather than character-by-character.

Both functions need a pattern and an x argument, where the pattern is the regular expression you want to match for, and the x argument is the character vector from which matches should be sought.


sv <- "Infosys is currently trading at 1435 Rs."

op <- grepl("\\d+", sv)



[1] TRUE

In this example, we are searching if the string vector contains a numeric value or not. It returns TRUE because it contains the numeric value.

That is it for this tutorial.

Leave a Comment