Samuel Shamiri
Samuel Shamiri

Reputation: 121

R -Multiple conditional matching in a string

Is there a better way to do a string conditional match? for example the word farm is conditionally matched with rose, floral and tree. ideally I would like to do the matching without repeating farm

str = c('rose','farm','rose farm','floral', 'farm floral', 'tree farm')
grep("((?=.*farm)(?=.*rose)|(?=.*farm)(?=.*floral)|(?=.*farm)(?=.*tree))", str, value = TRUE,,perl = TRUE)

this return

[1] "rose farm"   "farm floral" "tree farm"

Upvotes: 2

Views: 438

Answers (1)

hwnd
hwnd

Reputation: 70750

One way — use a grouping construct to combine the set of words:

grep('(?=.*farm)(?=.*(?:rose|floral|tree))', str, value = TRUE, perl = TRUE)
# [1] "rose farm"   "farm floral" "tree farm"

Upvotes: 4

Related Questions