rstringsplit

string split on last comma in R


I'm not new to R but I am relatively new to regular expressions.

A similar question can be found in here, but it asks to split on the first comma rather than the last one.

As an example, if I use

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

I want to get

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

And if I use

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

I want to get

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

One viable way I think is to replace the last comma by something else such as

$, #, *, ...

then use

strsplit() 

to split the string by the one you replaced (Make sure it is unique!), but I'm more happy if you can deal with the problem using some built in function directly.

So how can I do that?


Solution

  • Here's one approach:

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

    You may want:

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

    As it will match if there is no space after the comma:

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