代码之家  ›  专栏  ›  技术社区  ›  socialscientist

提取通过相对于其他相对定位的字符定位定义的子字符串

  •  0
  • socialscientist  · 技术社区  · 8 年前

    我在一个字符向量中有许多URL,我正试图使用基R从中提取子字符串。我要提取两种类型的子字符串:

    • 字符串中最后一个斜杠(/)之后和最后一个下划线(\u)之前的子字符串。
    • 最后一个下划线(u)后面和substring.tar.gz之前的子字符串。

    我已经想出了一个解决办法,但它涉及许多不必要的步骤。有没有办法使用每个子字符串一个正则表达式来实现这一点?

    下面是我的工作示例:

    # An example URL
    a <- "https://cran.r-project.org/src/contrib/Archive/ggplot2/ggplot2_0.4.5.tar.gz"
    
    # Keep everything after the last slash
    b <- sub('.*\\/', '', a)
    # Keep everything before .tar.gaz
    c <- sub('.tar.*', '', b)
    
    # Extract desired strings based on underscore
    foo <- sub('.*\\_', '', c)
    bar <- sub('\\_.*', '', c)
    

    对于这个例子来说,使用基R是很重要的。

    3 回复  |  直到 8 年前
        1
  •  2
  •   pogibas    8 年前

    使用的解决方案 basename strsplit _ :

    sub(".tar.*", "", strsplit(basename(a), "_")[[1]])
    [1] "ggplot2" "0.4.5" 
    
        2
  •  1
  •   minem    8 年前

    使用 lookarounds :

    regmatches(a, regexpr('(?<=\\/)[^\\/]+(?=_)', a, perl = T))
    [1] "ggplot2"
    regmatches(a, regexpr('(?<=_)[^_]+(?=\\.tar\\.gz)', a, perl = T))
    [1] "0.4.5"
    
        3
  •  0
  •   Michał Turczyn    8 年前

    尝试以下模式: \/(?<package>[^\/]+)\_(?<version>[^\_\/]+).tar.gz$ .

    在匹配中,第一个捕获组名为 package 会给你 字符串中最后一个斜杠(/)之后和最后一个下划线(\u)之前的子字符串 第二,命名为 version ,会给你 最后一个下划线(u)后面和substring.tar.gz之前的子字符串。

    Demo