【问题标题】:Splitting a string with a number in the end in R在R中以数字结尾的字符串拆分
【发布时间】:2015-11-22 01:39:07
【问题描述】:

如何将包含数字(位数未知)的字符串拆分为两个字符串 - 数字和字符串的其余部分。请注意,字符串中可能有其他不应该受到影响的数字。例如:

"abc665abc12"   -> "abc665abc", "12"
"abc665abc 182" -> "abc665abc", "182"
"abc665abc0"    -> "abc665abc", "0"

谢谢!

【问题讨论】:

    标签: regex r split


    【解决方案1】:

    您也可以使用strsplit

    > x = c("abc665abc12", "abc665abc 182", "abc665abc0")
    > strsplit(x, "(?<=[A-Za-z])\\s*(?=\\d+$)", perl = TRUE)
    [[1]]
    [1] "abc665abc" "12"       
    
    [[2]]
    [1] "abc665abc" "182"      
    
    [[3]]
    [1] "abc665abc" "0"  
    

    【讨论】:

      【解决方案2】:

      这行得通:

      # op's example
      x = c("abc665abc12", "abc665abc 182", "abc665abc0")
      
      library(stringi)
      res = stri_match_first_regex(x, "^(.*?) ?([0-9]+)$")
      
      
           [,1]            [,2]        [,3] 
      [1,] "abc665abc12"   "abc665abc" "12" 
      [2,] "abc665abc 182" "abc665abc" "182"
      [3,] "abc665abc0"    "abc665abc" "0"  
      

      您想要的部分在第 2 列和第 3 列中,对应于正则表达式中的括号。

      【讨论】:

      【解决方案3】:

      当涉及到这样的事情时,我喜欢使用来自gsubfn 包的strapply

      library(gsubfn)
      strapply('abc665abc12', '(.*?) *(\\d+)$', c)[[1]]
      # [1] "abc665abc" "12" 
      

      如果你有一个字符向量,也是同一个概念:

      strapply(x, '(.*?) *(\\d+)$', c)
      

      【讨论】:

      • 或在基础 R strsplit(sub(' *(\\d+)$', ' \\1', x), ' ', fixed = TRUE)
      【解决方案4】:

      在基地:

      cbind(x,
            gsub("[ 0-9]+$", "", x), 
            gsub("^[a-z 0-9]+[a-z ]+", "", x))
      
           x                                
      [1,] "abc665abc12"   "abc665abc" "12" 
      [2,] "abc665abc 182" "abc665abc" "182"
      [3,] "abc665abc0"    "abc665abc" "0" 
      

      【讨论】:

        【解决方案5】:

        使用良好的旧正则表达式的解决方案:使用您的两个字符向量

            x <-"abc665abc12"
            y <- "abc665abc 182"
            patterns<-"[[:digit:]]+$"
            m1 <- regexpr(patterns,x) 
            m2 <-regexpr(patterns,y)
        

        现在regmatches(x,m1) 产生“12” n regmatches(y,m1) 产生“182”

        【讨论】:

          猜你喜欢
          • 2021-03-30
          • 1970-01-01
          • 2023-02-10
          • 2019-03-30
          • 2014-06-12
          • 1970-01-01
          • 2023-01-30
          • 2014-07-31
          • 1970-01-01
          相关资源
          最近更新 更多