R grepl() Function

The grepl() function in R is used for pattern matching and searching within strings. It’s a variation of the grep() function, where grepl() returns a logical vector suggesting whether a pattern is found in each element of a character vector.


grepl(pattern, x, ignore.case = FALSE, perl = FALSE,
      fixed = FALSE, useBytes = FALSE)


Name Description
pattern It is a regular expression or string for fixed=TRUE.
x It is a string, the character vector.
perl Logical. Should Perl-compatible regexps be used? Has priority been overextended?
fixed It is logical. If the TRUE, the pattern is a string to be matched. Overrides all conflicting arguments.
useBytes It is logical. If TRUE, the matching is done byte-by-byte rather than character-by-character.

Return value

It returns TRUE if a string contains the pattern; otherwise, it is FALSE.

Example 1: Searching for simple patterns in character vectors

Visual representation of the grepl() Function in R

In this figure, we are searching for character “K” in the vector rv, and if it matches, it returns TRUE; otherwise, it is FALSE.

rv <- c("KHUSHI", "KRUNAL", "MATE", "AUS")

grepl("K", rv)



Example 2: Using regular expressions

Using regular expressions with the grepl() function

In the figure, we check if the string sv contains any numeric digits. If there is a numeric digit, it returns TRUE; otherwise, it is FALSE.

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

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



[1] TRUE

Example 3: Passing ignore.case argument

Pass the ignore.case = TRUE to ignore the letters’ cases while searching for patterns. It will ignore whether the letters are in capital or small letters in the string.

In the below figure, we passed ignore.case = TRUE to the grepl() function, which means that no matter if the input character is small or capital, if it matches, it returns TRUE; otherwise, it returns FALSE.

Ignoring case while searching using grepl() function

rv <- c("khushi", "KRUNAL", "MATE", "AUS")
grepl("K", rv, ignore.case = T)



If we pass ignore.case = F or FALSE, it will only return the TRUE on the second position. It will check strictly.

Passing ignore.case = F or FALSE
Figure 4: ignore.case = F or FALSE
rv <- c("khushi", "KRUNAL", "MATE", "AUS")

grepl("K", rv, ignore.case = F)



You will find all the information about the grepl() method in the below image in RStudio.

Use grepl() function in RStudio
Figure 5: Use grepl() function in RStudio

The functions like grep(), grepl(), regexpr(), gregexpr(), and regexec() search for matches to argument patterns within every item of a character vector.

Leave a Comment