【问题标题】:R regex: match strings with two words near each other with exceptionR正则表达式:匹配两个单词彼此靠近的字符串,但有异常
【发布时间】:2019-05-04 02:10:21
【问题描述】:

我做了什么

我写了一个正则表达式匹配所有文本字符串与 "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

我想要得到什么

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

所以结果应该是这样的:

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


                         text id
1        NOT ART 6 ds as dd BV  2

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

【问题讨论】:

  • 只是为了澄清。你认为ART 6 ds as dd BVAT' 是匹配的吗
  • 不,只有`BV`应该匹配
  • 然后我会创建第二个&amp;!grepl("NOT?", text)subset(df, grepl("(ART)(?:\\W+\\w+){0,10}?\\W+(\\bBV\\b)", + perl=TRUE, + ignore.case = TRUE, + text) &amp; !grepl("NOT?", text, ignore.case = TRUE))
  • 我同意,但排除列表中的每个单词都可能出现在 "A" 之前或 "B" 之后的某个位置。我更正了样本数据
  • 那就试试library(stringr);str_extract(df$text, "(A\\w+\\b.*\\bBV\\b)") %&gt;% str_detect("NOT?") %&gt;% '!' %&gt;% magrittr::extract(df, ., )

标签: r regex grepl


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-03
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 2016-12-06
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多