-1

I need a regular expression that matches all space characters that are not within double quotes. I'm working on strings like this:

apple orange "g r a p e" pear "blue berry" pineapple

I need to split this string into individual items delimited by space characters, but only the space characters not enclosed in double quotes (stars for correct matches):

apple*orange*"g r a p e"*pear*"blue berry"*pineapple

How could I do this with a regular expression? From the little bit of digging I've done it seems like operations like this might not be regex's strength, so would it be better to split the string some other way? I'm using JavaScript.

  • What about nested escaped quotes? If there can be nested quotes, what escape symbol is? Please share the code you have tried. – Wiktor Stribiżew Nov 11 '20 at 17:37
  • Look at this question and imagine it says "spaces" instead of "commas" : https://stackoverflow.com/questions/1757065/java-splitting-a-comma-separated-string-but-ignoring-commas-in-quotes – Patrick Parker Nov 11 '20 at 17:45
  • 1
    Try to match what you want to keep instead of the spaces by which you want to split the string. – Thomas Nov 11 '20 at 17:50

2 Answers2

-1

To add on to Blindy's answer if you want to use the regex expression I suggest checking out this websites answer: https://javascript.info/regexp-groups

Effectively once you use the regex to create the match it will create two matched groups and you can tap into each one individually like so:

let str = 'apple orange "g r a p e" pear "blue berry" pineapple';

let tag = str.match(/(?:"[^"]+"|[^" ]+)?(\s+)/);

alert( tag[0] ); // apple, orange, "g r a p e", pear, "blue berry", pineapple 
alert( tag[1] ); // "  ", " ", " ", " ", " ", " ", " "
Antfere
  • 66
  • 6
-2
(?:"[^"]+"|[^" ]+)?(\s*)

You can see it in action here: https://regex101.com/r/MvC0vp/3

Blindy
  • 55,135
  • 9
  • 81
  • 120
  • you can pass a regex expression into the split function as its seperator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split – Coupe Nov 11 '20 at 17:33
  • @PatrickParker, a single space is captured as normal. – Blindy Nov 11 '20 at 17:55