开发者

javascript split string on multiple fields using regex

开发者 https://www.devze.com 2023-01-12 14:56 出处:网络
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\'\";

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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号