Home > Back-end >  How can I split a string on integer-comma substrings?
How can I split a string on integer-comma substrings?

Time:07-07

I want to split a string by commas but only with a number before comma. The number must be present in result groups.

It works fine until input string contains a comma without a number before, this comma should be a part of value group.

What should i change in the first regexp?

const doSplit = (parameter_type) => parameter_type.split(/(?!\d )\,\s/).map((option) => {
      const matches = option.match(/(?<value>. )\s(?<key>\d )$/)
      if(matches === null) {
        return {Error: {option, parameter_type}}
       }
      return matches.groups
 })
 
 const list_a = "No reaction 0, Up 1, Down 3, Stop 5, Position 1 6, Position 2 7, Position 3 8, Position 4 9, Individual position 10, Enable automatic sun protection 14"
 
 console.log(doSplit(list_a))
 
 const list_b = "End position, no overflow 0, End position   2% overflow 2, End position   5% overflow 5, End position   10% overflow 10, End position   20% overflow 20, Total travel time   10% Overflow 255"
 console.log(doSplit(list_b))
 

CodePudding user response:

You could do this with just one regex, and matchAll:

const regex = /\s*,?\s*(?<value>. ?)\s (?<key>\d )(?=,|$)/g;
const doSplit = (parameter_type) => 
    Array.from(parameter_type.matchAll(regex), ({groups}) => groups);
 
 const list_a = "No reaction 0, Up 1, Down 3, Stop 5, Position 1 6, Position 2 7, Position 3 8, Position 4 9, Individual position 10, Enable automatic sun protection 14"
 console.log(doSplit(list_a))
 
 const list_b = "End position, no overflow 0, End position   2% overflow 2, End position   5% overflow 5, End position   10% overflow 10, End position   20% overflow 20, Total travel time   10% Overflow 255"
 console.log(doSplit(list_b))

  • Related