My application has a search box that supports queries with the following structure:
Input: a string with the following structure:
<operand><phrase><category> <operand><phrase><category> ...
<operand>: can be + or - to denote include or exclude and is optional
<phrase>: can be a single word or a word or sentence surrounded by quotes
<category>: is surrounded by square brackets and can be either [c1], [c2], or [c3]
An example of one query:
+car "tart berries"[fruit] -"broccoli"[vegetable] "green onion"[vegetable] pepper[vegetable] -"my keys"[object]
Desired output :
[
["+", "car", ""],
["" , "tart berries","fruit"],
["-", "broccoli"., "vegetable"],
["" , "green onion", "vegetable"],
["" , "pepper", "vegetable"]
]
My code:
I use the following regex to capture groups:
let re = /([+-]?)(\w+|".+?")(\[fruit\]|\[vegetable\]|\[object\])?/gi
var str = '+car "tart berries"[fruit] -"broccoli"[vegetable] "green onion"[vegetable] pepper[vegetable] -"my keys"[object]'
for (const match of str.matchAll(re)) {
console.log(match);
}
Issue:
- Items get repeated multiple time:
["+car", "+", "car"]
[""tart berries"[fruit]", "", ""tart berries"", "[fruit]"]
- is there a way to exclude quotes from the results.
"tart berries" instead of ""tart berries""