5

我的 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"

它只解析第一个令牌,我无法弄清楚它为什么这样做。据我所知,由于!.起始非终端的末尾,部分匹配是不可能的。我怎样才能解决这个问题?

4

1 回答 1

10

匹配正在获取整个字符串,但捕获错误。请注意,'->' 的优先级高于串联,因此您可能需要将括号括起来,如下所示:

  EXPR        <- S? ( TERM ( (S OPERATOR)? S TERM )+ ) -> {}
于 2012-01-13T18:01:58.800 回答