Alex Rivera | Logout

Complete word matching using grepl in R

Asked 2011-06-29T23:02:46.790
25

Consider the following example:

> testLines <- c("I don't want to match this","This is what I want to match")
> grepl('is',testLines)
> [1] TRUE TRUE

What I want, though, is to only match 'is' when it stands alone as a single word. From reading a bit of perl documentation, it seemed that the way to do this is with \b, an anchor that can be used to identify what comes before and after the patter, i.e. \bword\b matches 'word' but not 'sword'. So I tried the following example, with use of Perl syntax set to 'TRUE':

> grepl('\bis\b',testLines,perl=TRUE)
> [1] FALSE FALSE

The output I'm looking for is FALSE TRUE.

Edit
Report

1 Answer

21

you need double-escaping to pass escape to regex:

> grepl("\\bis\\b",testLines)
[1] FALSE  TRUE
answered 2011-06-29T23:17:17.007

Your Answer