我的Lua应用程序的一部分是一个搜索栏,我试图让它理解布尔表达式。我正在使用LPeg,但是当前的语法给出了一个奇怪的结果:
> 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"
它只解析第一个令牌,我无法弄清楚为什么会这样做。据我所知,部分匹配是不可能的,因为在起始非终端的末尾有!.
。我该如何解决这个问题?
答案 0 :(得分:10)
匹配是获取整个字符串,但捕获是错误的。注意 ' - &GT;'具有比串联更高的优先级,所以你可能需要围绕这样的括号:
EXPR <- S? ( TERM ( (S OPERATOR)? S TERM )+ ) -> {}