【问题标题】:How to check for exact string of words如何检查确切的单词串
【发布时间】:2019-10-07 02:56:48
【问题描述】:

我正在尝试将大量单词与一列字符串进行匹配。这些词必须完全匹配。

我可以一次只用一个词,但对于多个词我会遇到一些问题。

x = c("red", "redish", "green", "greenish")
grepl("red|green", ignore.case=TRUE, x)

我希望它返回“红色”和“绿色”;但不会偏红或偏绿。

【问题讨论】:

    标签: r regex grepl


    【解决方案1】:

    正则表达式让您使用\\b 来表示单词边界:

    grepl("\\bred\\b|\\bgreen\\b", x, ignore.case = TRUE)
    # [1]  TRUE FALSE  TRUE FALSE
    

    如果您想匹配较长字符串中的单词,这将很有效:

    grepl("\\bred\\b|\\bgreen\\b",
          c("I want to match red", "But not Fred",
            "Green yes please", "ignore wintergreen"),
          ignore.case=TRUE)
    # [1]  TRUE FALSE  TRUE FALSE
    

    但是,如果你在做整个字符串匹配,正则表达式是多余的,相等匹配会快得多:

    tolower(x) %in% c("red", "green")
    [1]  TRUE FALSE  TRUE FALSE
    

    如果我们从patterns = c("red|green") 开始,我们可以得到上述任何一种情况:

    ## use this with `%in%`
    individual_words = unlist(strsplit(patterns, split = "\\|")) 
    
    ## or paste on the word boundaries for regex
    word_boundary_patterns = paste0("\\b", individual_words, "\\b", collapse = "|")
    

    【讨论】:

    • 谢谢 Gregor,很抱歉我应该提一下,我的单词列表非常大。我们可以在代码中添加 \\b...\\b 或 ^...$ 吗?我无法将它们添加到由 | 分隔的单词列表中,例如“red|green”。谢谢。
    • 谢谢!!这有帮助。
    • 有一些特殊情况我必须处理,它们有“-”,我需要将它们作为一个单词来阅读,也就是说,引用中的所有单词,比如 'spring-concert ' 等等。在下面的示例中,我只需要最后一个学期的 TRUE -- x = c('5-year-old', '17-year-old', '7-year-old', 'year-old ') grepl("\\byear-old\\b", ignore.case=TRUE, x) 。感谢您的帮助
    • 为此使用模式(?<!-)\\byear-old\\b,其中(?<!-) 表示“前面没有破折号”。您可以see here 如何定义单词边界。像这样的特殊情况将不得不特殊处理。
    【解决方案2】:

    您还可以使用^$ 分别指定字符串的开头和结尾:

    grepl("^red$|^green$", ignore.case = T, x)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-27
      • 1970-01-01
      相关资源
      最近更新 更多