【问题标题】:Extract words between numbers提取数字之间的单词
【发布时间】:2019-01-17 20:33:31
【问题描述】:

尝试在 R 中编写一些 regex 以在 R 中的字符向量中为每个字符串的数字之间提取一些单词。不幸的是,我的 regex 技能几乎无法应对挑战。
这是问题的一个例子和我最初的尝试:

x <- c("1 Singleword 1,234 342", "2 randword & thirdword 1,545 323", 
      "3 Anotherword wordagain Newword. 3,234 556")

m <- regexpr("[a-zA-Z]+\\s+", x, perl = TRUE)

regmatches(x, m)

这种方法只会产生

"Singleword ", "randword ", "Anotherword "

我需要的是

"Singleword", "randword & thirdword", "Anotherword wordagain Neword."

我相信它需要是某种regex 模式,它以一个字符开头(就像我目前拥有的那样),然后拉出所有内容,直到达到一个数字。

【问题讨论】:

    标签: r regex


    【解决方案1】:
    x <- c("1 Singleword 1,234 342", "2 randword & thirdword 1,545 323", 
           "3 Anotherword wordagain Newword. 3,234 556")
    
    m <- regexpr("[a-zA-Z].(\\D)+", x, perl = TRUE)
    
    regmatches(x, m)
    

    [1] "单字" "二字&三字"
    [3] "Anotherword wordagaining Newword。"

    我使用了https://regexr.com/,它是用来弄清楚如何编写正则表达式的备忘单。

    【讨论】:

    • 完美运行!
    【解决方案2】:

    使用sub

    > sub(".\\s(\\D+).*", "\\1", x)
    [1] "Singleword "   "randword & thirdword "  "Anotherword wordagain Newword. "
    

    使用str_extract

    > library(stringr)
    > str_extract(x, pattern = "\\D+")
    [1] " Singleword "  " randword & thirdword "  " Anotherword wordagain Newword. "
    

    【讨论】:

      【解决方案3】:

      样本数据

      x <- c("1 Singleword 1,234 342", "2 randword & thirdword 1,545 323", 
         "3 Anotherword wordagain Newword. 3,234 556")
      

      基础 R

      #replace als numbers and comma's with `""` (=nothing), 
      # also, trim whitespaces (thanks Markus!)
      trimws( gsub( "[0-9,]", "", x ) )
      

      [1] "Singleword" "randword &thirdword" "Anotherword wordagain Newword."

      字符串R

      library(stringr)
      str_extract(x, pattern = "(?<=\\d )[^0-9]+(?= \\d)")
      

      [1] "Singleword" "randword &thirdword" "Anotherword wordagain Newword."

      如果您想了解更多关于上述代码(以及其他答案)中正则表达式模式(工作原理)的信息,请查看它们的魔力(和解释):https://regex101.com/

      最后一个正则表达式的解释:https://regex101.com/r/QgERuZ/2

      【讨论】:

      • 您可以将您的base R 解决方案包装在trimws 中,即trimws(gsub( "[0-9,]", "", x))(很抱歉再次打扰您)。
      • sub('. ([A-z].*?).\\d.*','\\1',x)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 2012-04-13
      • 2019-08-18
      • 2018-12-31
      • 2019-06-24
      • 2012-10-21
      相关资源
      最近更新 更多