【问题标题】:How can I extract a string rowwise using regex?如何使用正则表达式逐行提取字符串?
【发布时间】:2020-04-24 09:48:14
【问题描述】:

我在数据框中有一列 filename,如下所示:

/testData/THQ/TAIRATE.20030314.190000.tif
/testData/THQ/TAIRATE.20030314.200000.tif
/testData/THQ/TAIRATE.20030314.210000.tif
/testData/THQ/TAIRATE.20030314.220000.tif

我想从中提取时间戳并将其存储为另一列。但我不熟悉正则表达式。到目前为止,我已经做到了:

tdat %>%
  dplyr::rowwise() %>% 
  dplyr::mutate(timestamp = str_extract(as.character(filename), "[^//TAIRATE]+$")) %>% 
  glimpse()

结果

.20030314.190000.tif
.20030314.200000.tif
.20030314.210000.tif
.20030314.220000.tif

预期结果

20030314190000
20030314200000
20030314210000
20030314220000

问题:如何编写正确的正则表达式或有更好的方法?

【问题讨论】:

  • 试试str_extract(as.character(filename), "(?<=TAIRATE\\.)\\d+")
  • @WiktorStribiżew 谢谢!但这是删除点之后的所有内容。获取20030314
  • 没错,那么str_replace(as.character(filename), ".*TAIRATE\\.(\\d+)\.(\\d+).*", "\\1\\2") 呢?这将产生副作用:如果没有找到匹配项,您最终将保持整个文件名不变。

标签: r regex dplyr


【解决方案1】:

str_extract 和其他此类函数是矢量化的,您不需要逐行。

在这种情况下,您可以使用sub 在基础 R 中执行此操作。

sub('.*TAIRATE\\.(\\d+)\\.(\\d+).*', '\\1\\2', df$filename)
#[1] "20030314190000" "20030314200000" "20030314210000" "20030314220000"

【讨论】:

  • @maximusdooku 与my comment 中的注释相同:这将产生副作用:如果未找到匹配项,则整个文件名将保持不变
  • @WiktorStribiżew 谢谢你的警告!另外,作为旁注 - 什么是一个很好的资源来了解正则表达式以使其工作?我总是避免学习它。
  • @maximusdooku 我不知道你的正则表达式知识水平:) 所以我只能建议在regexone.com 上所有课程,阅读regular-expressions.inforegex SO tag description(还有许多其他链接很棒的在线资源),以及名为 What does the regex mean 的社区 SO 帖子。另外,rexegg.com 值得一看。
  • @maximusdooku 对于 R,另请参阅 this answer of mine
【解决方案2】:

当然不如@akrun 的解决方案优雅,但这个也有效:

paste0(unlist(str_extract_all(filename, "[0-9]+")), collapse = "")

数据:

filename <- "/testData/THQ/TAIRATE.20030314.190000.tif"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-02
    • 2010-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 2021-03-09
    相关资源
    最近更新 更多