4

我正在尝试使用 PEG.js 构建一个简单的解析器。我希望用户能够输入一系列关键字,它们之间有一个可选的“AND”,但我似乎无法获得可选和工作。它总是期待它,即使我已经用 ? (零或一)。

将此语法粘贴到http://pegjs.majda.cz/online

parse = pair+

pair = p:word and? { return p }

word = w:char+ { return w.join(""); }

char = c:[^ \r\n\t] { return c; }

and = ws* 'and'i ws*

ws = [ \t]

我的目标是将这些输入中的任何一个解析为 ["foo", "bar"] 的数组:

foo bar
foo and bar
4

3 回答 3

1

好的不要紧。我想到了。这是因为我将“and”前面的可选空格作为and规则的一部分,所以它期望规则的其余部分。我只需要将它移出,进入配对规则,如下所示:

parse = pair+
pair  = p:word ws* and? { return p }
word  = w:char+ { return w.join(""); }
char  = c:[^ \r\n\t] { return c; }
and   = 'and'i ws*
ws    = [ \t]
于 2013-10-05T16:27:20.860 回答
1

I know this is a very old question, but seeing how it wasn't answered and someone might stumble upon it I'd like to submit my answer:

Program
    = w1:$Word _ wds:(_ "and"? _ w:$Word { return w; })* _  {
        wds.unshift(w1);
        return wds;
    }
Word 
    = [a-zA-Z]+
 _
    = [ ,\t]*

The "and" is optional and you can add as many words as you want. The parser will skip the "and"'s and return a list of the words. I took the liberty of removing commas.

You can try it out https://pegjs.org/online with a string like:

carlos, peter, vincent, thomas, and shirly

Hope it helps someone.

于 2017-01-13T12:20:24.563 回答
0

这是我的答案:

start
  = words

words
  = head:word tail:(and (word))* {
    var words = [head];
    tail.forEach(function (word) {
      word = word[1];
      words.push(word);
    })
    return words;
  }

and
  = ' and '
  / $' '+

word
  = $chars

chars 'chars'
  = [a-zA-Z0-9]+
于 2014-01-09T09:11:13.593 回答