【问题标题】:splitting strings using regex in R在 R 中使用正则表达式拆分字符串
【发布时间】:2020-08-16 01:27:39
【问题描述】:

我有一个非常长的字符串列表,看起来像下面的,我想把它分成几部分。

strings<-c("https://www.website.com/stats/stat.227.y2020.eon.t879.html",
"https://www.website.com/stats/stat.229.y2019.eoff.t476.html")

所需的输出如下:

links                                     Year    Seas     Tour 
https://www.website.com/stats/stat.227.   y2020    eon     t879
https://www.website.com/stats/stat.229.   y2019   eoff     t476 

如何使用正则表达式实现这一点?

【问题讨论】:

    标签: r regex string


    【解决方案1】:

    使用str_match

    stringr::str_match(strings, '.*\\.(y\\d+)\\.(\\w+)\\.(t\\d+)')
    

    如果将strings 放入数据框中,则可以在tidyr::extract 中使用相同的正则表达式。

    tidyr::extract(data.frame(strings), strings, c("Year","Seas", "Tour"), 
                  '\\.(y\\d+)\\.(\\w+)\\.(t\\d+)', remove = FALSE)
    
    #                                                      strings  Year Seas Tour
    #1  https://www.pgatour.com/stats/stat.227.y2020.eon.t879.html y2020  eon t879
    #2 https://www.pgatour.com/stats/stat.229.y2019.eoff.t476.html y2019 eoff t476
    

    在这里,我们将数据捕获为 3 个部分(捕获组)

    第一部分 - 'y' 后跟一个数字

    第 2 部分 - 第 1 部分之后的下一个单词

    第三部分 't' 后跟一个数字。

    【讨论】:

      【解决方案2】:

      你可以使用 {unglue} :

      library(unglue)
      unglue::unglue_data(
        strings, "{links}.{Year=[^.]+}.{Seas=[^.]+}.{Tour=[^.]+}.html")
      #>                                    links  Year Seas Tour
      #> 1 https://www.website.com/stats/stat.227 y2020  eon t879
      #> 2 https://www.website.com/stats/stat.229 y2019 eoff t476
      

      这里的"[^.]+" 表示“一个或多个非点字符”,这就是我们想要的 Year、Seas 和 Tour。

      【讨论】:

        猜你喜欢
        • 2021-10-13
        • 2017-02-23
        相关资源
        最近更新 更多