Reputation: 121
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
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