【问题标题】:Remove parts of pattern from string with gsub使用 gsub 从字符串中删除部分模式
【发布时间】:2016-02-29 02:55:17
【问题描述】:

我有一个这样的字符串列表(省略 58*5 例):

participant_01_Bullpup_1.xml
participant_01_Bullpup_2.xml
participant_01_Bullpup_3.xml
participant_01_Bullpup_4.xml
participant_01_Bullpup_5.xml
#...Through to...
participant_60_Bullpup_1.xml
participant_60_Bullpup_2.xml
participant_60_Bullpup_3.xml
participant_60_Bullpup_4.xml
participant_60_Bullpup_5.xml

我想在这些上使用 gsub 以便最终得到(仅示例):

01_1
60_5

目前,我的代码如下:

fileNames <- Sys.glob("part*.csv")

for (fileName in fileNames) {
    sample <- read.csv(fileName, header = FALSE, sep = ",")
    part   <- gsub("[^0-9]+", "", substring(fileName, 5, last = 1000000L))
    print(part)
}

这会产生以下字符串(示例):

011
605

但是,我不知道如何在这些字符串之间保留一个下划线。

【问题讨论】:

    标签: regex r gsub


    【解决方案1】:

    试试

    sub('[^0-9]+_([0-9]+_).*([0-9]+).*', '\\1\\2', str1)
    #[1] "01_1"
    

    library(stringr)
    sapply(str_extract_all(str1, '\\d+'), paste, collapse='_')
    

    数据

    str1 <- 'participant_01_Bullpup_1.xml'
    

    【讨论】:

    • 对不起,我要把 sapply 放在 sub 之前吗?脚本的第一部分就像一个奇迹
    • @MichaelAnderson 在sub 之前不需要sapply。您可以处理整个列,即sub(...., yourdf$yourcolumn)
    • 我认为 str_extract_all_regex() 可能会带来更好的性能。
    【解决方案2】:

    这里还有一些选项(使用 akrun 的 str1):

    gsub("[^0-9_]+|(?<=\\D)_", "", str1, perl=TRUE)
    #[1] "01_1"
    sub(".+?(\\d+_).+?(\\d+).+", "\\1\\2", str1, perl=TRUE)
    #[1] "01_1"
    sub(".+?(\\d+).+?(\\d+).+", "\\1_\\2", str1, perl=TRUE)
    #[1] "01_1"
    paste(strsplit(str1, "\\D+")[[1]][-1], collapse="_")
    #[1] "01_1"
    

    如果您的模式确实如此一致(即在第一个数字之前有 12 个字符,然后是 8 个字符直到下一组数字,然后是 4 个更多字符),那么您可以明确地使用量词:

    sub(".{12}(\\d+_).{8}(\\d+).{4}", "\\1\\2", str1)
    #[1] "01_1"
    

    或简单地使用适当的索引访问字符:

    paste0(substr(str1, 13, 15), substr(str1, 24, 24))
    #[1] "01_1"
    

    【讨论】:

      猜你喜欢
      • 2012-07-31
      • 2021-01-28
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多