split character data into numbers and letters

后端 未结 7 1759
没有蜡笔的小新
没有蜡笔的小新 2020-12-02 15:45

I have a vector of character data. Most of the elements in the vector consist of one or more letters followed by one or more numbers. I wish to split each element in the

7条回答
  •  广开言路
    2020-12-02 16:25

    Late answer, but another option is to use strsplit with a regex pattern which uses lookarounds to find the boundary between numbers and letters:

    var <- "ABC123"
    strsplit(var, "(?=[A-Za-z])(?<=[0-9])|(?=[0-9])(?<=[A-Za-z])", perl=TRUE)
    [[1]]
    [1] "ABC" "123"
    

    The above pattern will match (but not consume) when either the previous character is a letter and the following character is a number, or vice-versa. Note that we use strsplit in Perl mode to access lookarounds.

    Demo

提交回复
热议问题