R正则表达式:匹配两个单词彼此靠近的字符串,但有例外

R regex: match strings with two words near each other with exception

我做了什么

我写了一个正则表达式来匹配所有带有 "A""BV" 的文本字符串,使用本教程之间有 0-10 个单词:https://www.regular-expressions.info/near.html

df<- data.frame(text=c("ART 6 dasd asd NOT art 2 BV","NOT ART 6 ds as dd BV","ART 6 NO BV"),
                id=c(1,2,3))



subset(df, grepl("(ART)(?:\W+\w+){0,10}?\W+(\bBV\b)",
                   perl=TRUE,
                   ignore.case = TRUE,
                   text))


                         text id
1 ART 6 dasd asd NOT art 2 BV  1
2       NOT ART 6 ds as dd BV  2
3                 ART 6 NO BV  3

我想得到什么

现在我想重写正则表达式,如果在 0-10 个单词中出现列表中的任何单词(即示例数据中的 NOTNO),它不匹配在 "A" 和 "BV" 之间。

所以结果看起来像:

subset(df, grepl("NEWREGEX",
                   perl=TRUE,
                   ignore.case = TRUE,
                   text))


                         text id
1        NOT ART 6 ds as dd BV  2

我想我可以使用类似 ?! 的东西,但我想不通

感谢 akrun 我们有了一个非常好的解决方案:

library(stringr)
str_extract(df$text, "(A\w+\b.*\bBV\b)") %>% str_detect("NOT?") %>% '!' %>% magrittr::extract(df, ., )