Regex splitting on whitespace exept in quotes or square brackets

Viewed 199

So as the title says, I try to split a string by whitespace but not inside double quotes or square brackets

I have tried this but it gives me error:
.match(/(?|[([^]])]|"([^"])"|(\w+))/g);

And to modify this which works with roundbrackets instead of square brackets, but without luck:
/([^)]+?[)]|[""].+?[""]|[^ ]+/g

What I want:

example dummy string:
sometext here " stuff here " [hello " otherstuff " 3] "goodbye"
the response I want:
[sometext, here, " stuff here ", [hello " otherstuff " 3], "goodbye"]

If anyone knows how to write the correct regex, I would be forever grateful

2 Answers

What about something like this:

  var str = `sometext here " stuff here " [hello " otherstuff " 3] "goodbye"`;
  var patt = /(\w+)|(\".+?\")|(\[.+?\])/g;
  var result = str.match(patt);
  console.log(result);

You either match on a word, stuff between quotes or stuff between square brackets! Here's your example using regexr.

enter image description here

Use

string.match(/"[^"]*"|\[[^\][]*]|[^\s\][]+/g)

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  "                        '"'
--------------------------------------------------------------------------------
  [^"]*                    any character except: '"' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  "                        '"'
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  \[                       '['
--------------------------------------------------------------------------------
  [^\][]*                  any character except: '\]', '[' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  ]                        ']'
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  [^\s\][]+                any character except: whitespace (\n, \r,
                           \t, \f, and " "), '\]', '[' (1 or more
                           times (matching the most amount possible))

Code:

const string = `some.text here " stuff here " [hello " otherstuff " 3] "good-bye"`
console.log(string.match(/"[^"]*"|\[[^\][]*]|[^\s\][]+/g))

Related