Austin
Austin

Reputation: 121

Grep for a regular expression in R

I have a vector of character strings which I need to grep through.

The term I would like to grep is "A-10", but I would like it only to pick up rows where "A-10" is an independent word (e.g. "A-10 aircraft maintenance" and NOT "WQDA-10-ASP").

Which regular expression(s) would allow me to grep for "A-10" as an separate word and not part of a different word or string?

Upvotes: 1

Views: 2274

Answers (1)

DunderChief
DunderChief

Reputation: 726

How about this:

abc <- c('A-10 maintanance', 'WQDA-10-ASP')
grep('(^|\\s)A-10($|\\s)', abc)

where (^|\\s) means beginning of string or whitespace, and ($|\\s) means end of line or whitespace

Also take a look at the stringr package if you want some nice regex functions.

Upvotes: 4

Related Questions