我的Lua应用程序的一部分是一个搜索栏,我试图让它理解布尔表达式.我正在使用LPeg,但是当前的语法给出了一个奇怪的结果: re, yajl = require're', require'yajl' querypattern = re.compile[=[ QUERY - (
> re, yajl = require're', require'yajl' > querypattern = re.compile[=[ QUERY <- ( EXPR / TERM )? S? !. -> {} EXPR <- S? TERM ( (S OPERATOR)? S TERM )+ -> {} TERM <- KEYWORD / ( "(" S? EXPR S? ")" ) -> {} KEYWORD <- ( WORD {":"} )? ( WORD / STRING ) WORD <- {[A-Za-z][A-Za-z0-9]*} OPERATOR <- {("AND" / "XOR" / "NOR" / "OR")} STRING <- ('"' {[^"]*} '"' / "'" {[^']*} "'") -> {} S <- %s+ ]=] > = yajl.to_string(lpeg.match(querypattern, "bar foo")) "bar" > = yajl.to_string(lpeg.match(querypattern, "name:bar AND foo")) > = yajl.to_string(lpeg.match(querypattern, "name:bar AND foo")) "name" > = yajl.to_string(lpeg.match(querypattern, "name:'bar' AND foo")) "name" > = yajl.to_string(lpeg.match(querypattern, "bar AND (name:foo OR place:here)")) "bar"
它只解析第一个令牌,我无法弄清楚它为什么会这样做.据我所知,部分匹配是不可能的,因为!在起始非终端的末尾.我怎样才能解决这个问题?
匹配是获取整个字符串,但捕获是错误的.注意‘ – >’具有比串联更高的优先级,所以你可能需要括号围绕这样的事情:
EXPR <- S? ( TERM ( (S OPERATOR)? S TERM )+ ) -> {}