R中的grepl()使用具有多个AND,OR的复杂模式

grepl() in R using complex pattern with multiple AND, OR

是否可以在 grepl() 中使用这样的 pattern(见下文)?

(poverty OR poor) AND (eradicat OR end OR reduc OR alleviat) AND extreme

目标是确定一个句子是否符合使用模式 ifelse(grepl(pattern, x, ignore.case = TRUE),"Yes","No")

例如,如果x = "end extreme poverty in the country",它将return "Yes",而如果x = "end poverty in the country" , 它会 return “否”。

较早的 post 仅适用于单一工作,例如 poor AND eradicat AND extreme,但不适用于我的情况。有什么方法可以实现我的目标吗?

试过这个,pattern = "(?=.*poverty|poor)(?=.*eradicat|end|reduce|alleviate)(?=.*extreme)",但它不起作用。错误是'Invalid regexp'

要使用所有 3 个断言,您可以使用非捕获组对单词进行分组。

^(?=.*(?:poverty|poor))(?=.*extreme)(?=.*(?:eradicat|end|reduc|alleviat)).+
  • ^ 字符串开头
  • (?=.*(?:poverty|poor)) 断言贫穷或贫穷
  • (?=.*extreme)断言极端
  • (?=.*(?:eradicat|end|reduc|alleviat)) 断言根除或结束或减少或缓解
  • .+ 匹配整行例如

Regex demo

对于 grepl,您必须使用 perl=T 启用 PCRE 进行环视。

grepl('^(?=.*(?:poverty|poor))(?=.*extreme)(?=.*(?:eradicat|end|reduc|alleviat)).+', v, perl=T)