up vote 0 down vote favorite

I'm trying to build a handy dsl-ish query ability into my javascript.

given:

var query = "lastName = 'smith' and firstName = 'jack' or city = 'vancouver'";

what's the most elegant way of parsing this sql-esque string into usable objects such as:

[
{
 field:'lastName',
 operator:'=',
 value:'smith',
 join:'and'
},
{
 field:'firstName',
 operator:'=',
 value:'jack',
 join:'or'
},
{
 field:'city',
 operator:'=',
 value:'vancouver'
}
]

Before I start hopelessly looping I figured there would be some regex master that had a one-liner.

link|flag

42% accept rate
1  
Are you crazy? lol :) – Topera Aug 23 at 21:17
If you are querying from a database PLEASE DONT use a regex. loop and validate each element before send to the backend. – Byron Whitlock Aug 23 at 21:20
Do you have rules for precedence? (ie. and before or) – Tmdean Aug 23 at 21:23
yes, rules for precedence. – Scott Aug 23 at 23:04

1 Answer

up vote 0 down vote

Create a grammar (EBNF or BNF) and then write a parser for it. Not only will you have more hair left on your head (you're going to end up pulling your hair out if you try to do this with regular expressions!), you will learn something new and cool :).

If you write a recursive-descent parser, you can easily represent your query as a tree.

Here's an EBNF to get you started:

query            ::= criterion { criterion }
criterion        ::= boolean-operator { filter }
boolean-operator ::= "not" | "or" | "and"
filter           ::= variable, "=", value
link|flag

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.