split strings on first and last commas

后端 未结 5 1971
生来不讨喜
生来不讨喜 2021-01-13 16:05

I would like to split strings on the first and last comma. Each string has at least two commas. Below is an example data set and the desired result.

A similar ques

5条回答
  •  孤独总比滥情好
    2021-01-13 16:38

    You can use the \K operator which keeps text already matched out of the result and a negative look ahead assertion to do this (well almost, there is an annoying comma at the start of the middle portion which I am yet to get rid of in the strsplit). But I enjoyed this as an exercise in constructing a regex...

    x <- '123,34,56,78,90'
    strsplit( x , "^[^,]+\\K|,(?=[^,]+$)" , perl = TRUE )
    #[[1]]
    #[1] "123"       ",34,56,78" "90"
    

    Explantion:

    • ^[^,]+ : from the start of the string match one or more characters that are not a ,
    • \\K : but don't include those matched characters in the match
    • So the first match is the first comma...
    • | : or you can match...
    • ,(?=[^,]+$) : a , so long as it is followed by [(?=...)] one or more characters that are not a , until the end of the string ($)...

提交回复
热议问题