javascriptjavaregexreadfileto-json

Split with Regex before sequence appears


I have a text file with following content:

Test, [636,13,"be738jsk","some, text",js]

I want to read this content into an Array. I currently use JavaScript with regex to split into substrings directly into an array. As regex i have: line.split(/,\s\[|",|,"|","/);

The problem is, i have some sentences like in the example with a "," in it and i don't want to split there. So i tried to say in the regex, "split after , and everthing except whitespace". The problem is, it also cuts out the "everything" after the ,

Example:

Test, [63737,33,"bla,blablba",737]

When i use this regex:

Line.split(/,"|,\s\[|",|,[^\s]/); Then it cut's out the 3 from 33 :(


Solution

  • You can use

    const text = 'Test, [636,13,"be738jsk","some, text",js], "[Blablba] Blablba"';
    console.log(
      Array.from(text.matchAll(/\w+|"([^"]*)"/g), x => x[1] ?? x[0])
    )

    Output:

    [
      "Test",
      "636",
      "13",
      "be738jsk",
      "some, text",
      "js",
      "[Blablba] Blablba"
    ]
    

    Here, \w+|"([^"]*)" matches one or more word chars or any zero or more chars other than double quotation marks (captured into Group 1) in between double quotation marks. The x => x[1] ?? x[0] part takes Group 1 values if defined, else, it keeps the whole match value.