【问题标题】:R: using \\b and \\B in regexR:在正则表达式中使用 \\b 和 \\B
【发布时间】:2020-04-22 07:24:12
【问题描述】:

我阅读了关于 regex 的内容并跨越了单词边界。我找到了一个question,它是关于\b\B 之间的区别。使用此问题中的代码不会给出预期的输出。这里:

grep("\\bcat\\b", "The cat scattered his food all over the room.", value= TRUE)
# I expect "cat" but it returns the whole string.

grep("\\B-\\B", "Please enter the nine-digit id as it appears on your color - coded pass-key.", value= TRUE)
# I expect "-" but it returns the whole string.

我使用问题中描述的代码,但建议使用两个反斜杠here。使用一个反斜杠也不起作用。我做错了什么?

【问题讨论】:

    标签: r regex string


    【解决方案1】:

    您可以使用regexprregmatches 来获得匹配。 grep 给出了它击中的位置。你也可以使用sub

    x <- "The cat scattered his food all over the room."
    regmatches(x, regexpr("\\bcat\\b", x))
    #[1] "cat"
    sub(".*(\\bcat\\b).*", "\\1", x)
    #[1] "cat"
    
    x <- "Please enter the nine-digit id as it appears on your color - coded pass-key."
    regmatches(x, regexpr("\\B-\\B", x))
    #[1] "-"
    sub(".*(\\B-\\B).*", "\\1", x)
    #[1] "-"
    

    对于超过 1 场比赛,请使用 gregexpr:

    x <- "1abc2"
    regmatches(x, gregexpr("[0-9]", x))
    #[[1]]
    #[1] "1" "2"
    

    【讨论】:

    • 我喜欢你的答案使用 R 基础。我有另一个例子,其中模式在字符串中出现多次。在stringr 中,我们可以为多次出现执行str_extract_all("1abc2", "[0-9]")(将返回1 2)。但是regmatches("1abc2", regexpr("[0-9]", "1abc2")) 只返回 1。有没有办法用你的方法做到这一点?
    • 是:使用gregexpr 代替regexpr。我在答案中添加了它。
    【解决方案2】:

    grep返回整个字符串,因为它只是查看匹配是否存在于字符串。如果要提取cat,需要使用str_extractfrom package stringr等其他函数:

    str_extract("The cat scattered his food all over the room.", "\\bcat\\b") 
    [1] "cat"
    

    bB之间的区别在于b标记单词边界,而B是它的否定。也就是说,\\bcat\\b 仅在 cat 由空格分隔时匹配,而 \\Bcat\\B 仅在 cat 在单词内时匹配。例如:

    str_extract_all("The forgot his education and scattered his food all over the room.", "\\Bcat\\B") 
    [[1]]
    [1] "cat" "cat"
    

    这两个匹配来自educationscattered

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      • 2021-07-15
      • 2022-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多