Skip to contents

Count regex matches within each element of a character vector

Usage

grepn(pattern, x, ignore.case = TRUE)

Arguments

pattern

pattern to search for, passed to gregexec()

x

a vector of character strings to search within

ignore.case

passed to gregexec()

Value

vector of numbers, same length as x

Details

  • grepn() counts matches for one pattern across a character vector.

  • grepns() handles multiple patterns and can return either a matrix of counts per string or a vector summarizing hits per pattern.

  • grepls() handles multiple patterns and returns logical presence/absence results rather than counts.

Examples

 grepn("x", c("0 abc", "1 uppercase X", "1 xyz", "2 xx", "3 x x x"))
 grepn("x", c("0 abc", "1 uppercase X", "1 xyz", "2 xx", "3 x x x"), ignore.case = FALSE)

 grepns(c("x", "y"), c("yes", "yx", "this 1 has some x x xxxxx"))
 grepns(c("hi", "other", 'x'), c("said hi ther hi hi hi e", 'hi', 'another', 'none'),
         rowperx = TRUE, count1perx = TRUE)
 grepns(c("hi", "other", 'x'), c("said hi ther hi hi hi e", 'hi', 'another', 'none'),
         rowperx = FALSE, count1perx = TRUE)
 grepns(c("hi", "other", 'x'), c("said hi ther hi hi hi e", 'hi', 'another', 'none'),
         rowperx = TRUE, count1perx = FALSE)
 grepns(c("hi", "other", 'x'), c("said hi ther hi hi hi e", 'hi', 'another', 'none'),
         rowperx = FALSE, count1perx = FALSE)

 grepls(c("hi", "other", 'x'), c("said hi ther hi hi hi e", 'hi', 'another', 'none'),
   rowperx = TRUE)
 grepls(c("hi", "other", 'x'), c("said hi ther hi hi hi e", 'hi', 'another', 'none'),
   rowperx = FALSE)