【问题标题】:Regular expression to extract words that starts with a pattern, but ends before symbols or spaces正则表达式提取以模式开头但在符号或空格之前结束的单词
【发布时间】:2022-01-24 01:11:28
【问题描述】:

我有以下示例proc 作为正则表达式

x <- "carr proc proc_ proca select procb() procth;"
pattern <- "proc"

预期的结果是

"proc" "proca" "procb" "procth"

可以是列表或向量。

我用 stringr::str_extract_all 尝试了其他几个正则表达式,但无法得到我想要的所有单词。

【问题讨论】:

  • pattern &lt;- "\\bproc\\w*"
  • 不,这不会提供预期的输出,也不会提供重复链接
  • 试试str_extract_all(x, "\\bproc([a-z]+|\\b)")[[1]]# [1] "proc" "proca" "procb" "procth"

标签: r regex string tidyverse stringr


【解决方案1】:

使用

pattern <- "\\bproc[[:alnum:]]*\\b"

regex proof

解释

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  proc                     'proc'
--------------------------------------------------------------------------------
  [[:alnum:]]*             any character of: letters and digits (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

【讨论】:

    【解决方案2】:

    这个怎么样?

    > unique(agrep(pattern, unlist(strsplit(x, "[^[:alpha:]]+")), value = TRUE))
    [1] "proc"   "proca"  "procb"  "procth"
    

    【讨论】:

      猜你喜欢
      • 2011-01-24
      • 1970-01-01
      • 1970-01-01
      • 2015-06-24
      • 2017-01-29
      • 2020-01-07
      • 1970-01-01
      • 2013-11-23
      • 1970-01-01
      相关资源
      最近更新 更多