【问题标题】:r- grepl to find matching strings in any orderr- grepl 以任何顺序查找匹配的字符串
【发布时间】:2020-01-26 06:51:36
【问题描述】:

我有一个匹配的字符串。需要查找匹配多个字符串(全部/全部)和任意顺序的文本:

Text1 : "I have no intention to make illegal parking along the road or cause obstruction."

Text2 : "I have no intention to make illegal parking along the road or cause damage."

我的代码:

    mynames=c("illegal parking" , "obstruction")
grepl(paste(mynames, collapse='|'), Text1, ignore.case=TRUE)

当我通过 Text1Text2 - 我得到 TRUE - 对于两者; 但是我需要TRUEText1FALSEText2。当只有两个字符串都存在时,它应该会产生 - 它可以在文本中以任何顺序出现。

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    |in 正则表达式的意思是“或”。这就是为什么它在两个文本上都是 TRUE 的。 您必须测试"obstruction" 是否跟在"illegal parking" 后面(中间有或没有),在正则表达式中这是"illegal parking.*obstruction",或者如果您有相反的方式,所以"illegal parking.*obstruction|obstruction.*illegal parking"

    grepl("illegal parking.*obstruction|obstruction.*illegal parking", Text1, ignore.case=TRUE)
    

    【讨论】:

      【解决方案2】:

      您可以测试str_extract_all() 的结果以查看两者是否匹配。这种方法意味着您不必担心订单。

      library(stringr)
      library(purrr)
      
      map_lgl(str_extract_all(c(Text1, Text2), paste(mynames, collapse='|')), ~all(mynames %in% .x))
      
      [1] TRUE FALSE
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-12-27
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 2022-01-17
        • 2019-07-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多