【问题标题】:Regex in R: efficiently extracting text before pattern and number immediatelly after patternR中的正则表达式:有效地提取模式之前的文本和模式之后的数字
【发布时间】:2021-06-06 22:33:00
【问题描述】:

假设在 R 中,我有许多由单词和数字混合组成的字符串,有一个共同点:在所有字符串中,总是有一个模式 zzzz 后跟一个空格,然后是一些未知数字。

例如:

x <- "many words, some number like 908, then zzzz 145 and some other numbers like 377 and so on"

然后,我要做的是提取 both 重复模式 zzzz 之后的数字,以及它之前的文本。

跟着@​​987654321@,我知道如何提取模式后面的数字了:

regmatches(x, gregexpr("zzzz \\K\\d+", x, perl=TRUE))

返回"145",上面有x 示例。我试图找到的是最有效的方式(因为我有数百万个字符串要评估)来检索模式之后的数字以及它之前的内容,这意味着返回向量:

"many words, some number like 908, then " "145"

在 R 中实现这一目标的最有效方法是什么?

【问题讨论】:

    标签: r regex gsub


    【解决方案1】:

    我们可以提取两组数据。

    1. zzzz 模式之前的所有内容
    2. 数字后跟zzzz
    strcapture('(.*) zzzz (\\d+)', x, list(col1 = character(), col2 = numeric()))
    
    #                                    col1 col2
    #1 many words, some number like 908, then  145       
    

    【讨论】:

    • 谢谢!我很抱歉,只是澄清一下:模式之前并不总是有一个数字。所以我认为这可以进一步简化,对吧?
    • 好的,这真的很好用,谢谢。出于学习目的的一个好奇心:(如果值得提出一个新问题,请告诉我,我会发布它):是否可以将该解决方案用于不止一个模式检查?我的意思是,假设在不同的字符串中有zzzz xyz 在所需的数字之前。我可以用'(.*) zzzz (\\d+) | (.*) xyz (\\d+)'. But here, that understandably throws the error The number of captures in 'pattern' != 'length(proto)'` 来找到这些数字。
    • 您可以使用此模式将第二个模式设为可选:'(.*) zzzz (?:xyz\\s)?(\\d+)' 所以这里'xyz\\s' 是可选的非捕获组。
    【解决方案2】:

    这是使用strsplitsub 的基本R 选项:

    x <- "many words, some number like 908, then zzzz 145 and some other numbers like 377 and so on"
    parts <- strsplit(x, "\\bzzzz\\s+")[[1]]
    parts[2] <- sub("\\s+.*$", "", parts[2])
    parts
    
    [1] "many words, some number like 908, then "
    [2] "145"
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-20
      • 2014-12-06
      相关资源
      最近更新 更多