1

I have a string:

'"Apples" AND "Bananas" OR "Gala Melon"'

I would like to convert this to an array

arr = ['"Apples"', 'AND', '"Bananas"', 'OR', '"Gala Melon"']

I don't know if I can do it with a regular expression. I'm beginning to think I may have to parse each character at a time to match the double quotes.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
spinners
  • 2,449
  • 3
  • 23
  • 34
  • 2
    Search for "JavaScript CSV parser" - it seems to be quite the same format – Bergi Feb 13 '13 at 12:20
  • possible duplicate of [Javascript code to parse CSV data](http://stackoverflow.com/questions/1293147/javascript-code-to-parse-csv-data) – mplungjan Feb 13 '13 at 12:28
  • See http://stackoverflow.com/q/8493195/1048572 or http://stackoverflow.com/q/1293147/1048572 and replace commata with spaces – Bergi Feb 13 '13 at 12:33
  • @Bergi it's not the spaces.. it's not the same thing – Lipis Feb 13 '13 at 14:19

1 Answers1

5
input = '"Apples" AND "Bananas" OR "Gala Melon"'

output = input.match(/\w+|"[^"]+"/g)
// output = ['"Apples"', 'AND', '"Bananas"', 'OR', '"Gala Melon"']

Explanation for the regex:

/ - start of regex
\w+ - sequence of word characters
| - or
"[^"]+" - anything quoted (assuming no escaped quotes)
/g - end of regex, global flag (perform multiple matches)

John Dvorak
  • 26,799
  • 13
  • 69
  • 83