Home > front end >  split a string on every odd positioned spaces
split a string on every odd positioned spaces

Time:11-04

I have strings of varying lengths in this format:

"/S498QSB 0 'Score=0' 1 'Score=1' 2 'Score=2' 3 'Score=3' 7 'Not administered'"

the first item is a column name and the other items tell us how this column is encoded

I want the following output:

/S498QSB
0 'Score=0'
1 'Score=1'
2 'Score=2'
3 'Score=3'
7 'Not administered'"

str_split should do it, but it's not working for me:

str_split("/S498QSB 0 'Score=0' 1 'Score=1' 2 'Score=2' 3 'Score=3' 7 'Not administered'",
              "([ ].*?[ ].*?)[ ]")

CodePudding user response:

You can use

str_split(x, "\\s (?=\\d \\s ')")

See the regex demo.

Details:

  • \s - one or more whitespaces
  • (?=\d \s ') - a positive lookahead that requires the following sequence of patterns immediately to the right of the current location:
    • \d - one or more digits
    • \s - one or more whitespaces
    • ' - a single quotation mark.
  • Related