【问题标题】:string split on last comma in R在R中的最后一个逗号处分割字符串
【发布时间】:2014-09-16 07:09:09
【问题描述】:

我对 R 并不陌生,但我对正则表达式比较陌生。

类似的问题可以在here 中找到,但它要求在第一个逗号而不是最后一个逗号上拆分。

例如,如果我使用

> lastcomma_strsplit("UK, USA, Germany", ", ")
[[1]]
[1] "UK"      "USA"     "Germany"

我想得到

[[1]]
[1] "UK, USA"     "Germany"

如果我使用

> lastcomma_strsplit("London, Washington, D.C., Berlin", ", ")
[[1]]
[1] "London"     "Washington" "D.C."       "Berlin"  

我想得到

[[1]]
[1] "London, Washington, D.C."       "Berlin"  

我认为一种可行的方法是将最后一个逗号替换为其他东西,例如

$, #, *, ...

然后使用

strsplit() 

用你替换的那个来分割字符串(确保它是唯一的!),但是如果你可以直接使用一些内置函数来处理这个问题,我会更高兴。

那我该怎么做呢?

【问题讨论】:

    标签: r string split comma


    【解决方案1】:

    这是一种方法:

    strsplit("UK, USA, Germany", ",(?=[^,]+$)", perl=TRUE)
    
    ## [[1]]
    ## [1] "UK, USA" " Germany"
    

    你可能想要:

    strsplit("UK, USA, Germany", ",\\s*(?=[^,]+$)", perl=TRUE)
    
    ## [[1]]
    ## [1] "UK, USA" "Germany"
    

    如果逗号后面没有空格,它将匹配:

    strsplit(c("UK, USA, Germany", "UK, USA,Germany"), ",\\s*(?=[^,]+$)", perl=TRUE)
    
    ## [[1]]
    ## [1] "UK, USA" "Germany"
    ## 
    ## [[2]]
    ## [1] "UK, USA" "Germany"
    

    【讨论】:

    • 谢谢,没关系,但是你没有把第二个逗号去掉……最好去掉第二个逗号。
    • 非常感谢,伙计!有什么建议或网站可以学习 R 中的正则表达式基础知识吗?
    • 两个地方:我在 SO 和 regular-expressions.info/rlanguage.html987654321@
    【解决方案2】:

    你可以使用stringi包中的stri_split函数

    x <- "USA,UK,Poland"
    stri_split_fixed(x,",") # standard split by comma
    [[1]]
    [1] "USA"    "UK"     "Poland"
    
    stri_split_fixed(x,",",n = 2) # set the max number of elements
    [[1]]
    [1] "USA"       "UK,Poland"
    

    不幸的是,没有参数可以更改拆分的起点(从开始/结束),但我们可以用另一种方式处理这个问题 - 使用 stri_reverse

    stri_split_fixed(stri_reverse(x),",",n = 2) #reverse
    [[1]]
    [1] "dnaloP" "KU,ASU"
    
    stri_reverse(stri_split_fixed(stri_reverse(x),",",n = 2)[[1]]) #reverse back
    [1] "Poland" "USA,UK"
    stri_reverse(stri_split_fixed(stri_reverse(x),",",n = 2)[[1]])[2:1] #and again :)
    [1] "USA,UK" "Poland"
    

    【讨论】:

      猜你喜欢
      • 2019-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-30
      • 2016-09-16
      • 2013-07-27
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多