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

使用正则表达式提取R中括号中的数字

  •  1
  • user1357015  · 技术社区  · 6 年前

    我试图从下面摘录22条:

    "Feb22 19  (22) 100  (Weeklys) "
    

    grep("\\(.*\\)", "Feb22 19  (22) 100  (Weeklys) ", value= TRUE
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   Tim Biegeleisen    6 年前

    我们可以尝试使用 sub 使用捕获组:

    x <- "Feb22 19  (22) 100  (Weeklys) "
    sub(".*\\((\\d+)\\).*", "\\1", x)
    
    [1] "22"
    

    .*     consume anything, up until the last
    \(     literal open parenthesis, which is then followed by
    (\d+)  one or more digits (which are captured)
    \)     followed by a closing parenthesis
    .*     followed by anything
    

    替代品是 \\1 在括号中包含一个数字,上面的调用 附属的 将实际返回原始输入字符串。如果你不喜欢这种行为,那么你就得做更多的工作。

        2
  •  2
  •   NelsonGon phoxis    6 年前

        string<-"Feb22 19 (22) 100 (Weeklys) "
        unlist(stringr::str_extract_all(string,"\\d{1,}(?=\\))"))
        #[1] "22"
    

    我最近被建议使用 simplify 虽然我发现 unlist 的产量更好。

    使用 stringr::str_extract_all(string,"\\d{1,}(?=\\))",simplify=TRUE)

        [,1]
    [1,] "22"