【问题标题】:R regex using stringr::str_detect and grepl don't seem to be matching "\\+" when it is surrounded by "\\b" [duplicate]使用 stringr::str_detect 和 grepl 的 R 正则表达式在被“\\b”包围时似乎不匹配“\\+” [重复]
【发布时间】:2019-06-26 02:46:55
【问题描述】:

我对正则表达式还是很陌生,我试图在长字符串中被“\\b”包围时检测带有“+”符号的单词,但 stringr 和 grepl 都给了我错误的结果。

这是我写的代码:

library(stringr)
str_detect("coversyl +", "\\bcoversyl(plus| plus|\\+| \\+)\\b")

输出为 FALSE,这是错误的。

正确的做法是什么?

【问题讨论】:

  • this相关
  • 正是这个。如果在用非单词字符/字符串的开始(结束)括起来时必须匹配,则不应在非单词字符旁边使用单词边界。如果您需要明确的单词边界,请使用 (?<!\w) / (?!\w) lookarounds: "(?<!\\w)coversyl(plus| plus|\\+| \\+)(?!\\w)"

标签: r regex stringr


【解决方案1】:

我的猜测是你的表达还可以,可能少了一个空格,

\\bcoversyl\\b\\s(\\bplus\\b|\\+)

Please see the demo for additional explanation.

如果我们可能需要多个空格,我们只需将 \\s 更改为 \\s+ 即可:

\\bcoversyl\\b\\s+(\\bplus\\b|\\+)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    相关资源
    最近更新 更多