[英]How to make optional word in PEG.js
I'm trying to build a simple parser with PEG.js. 我正在尝试使用PEG.js构建一个简单的解析器。 I want the user to be able to input a series of keywords, with an optional "AND" between them, but I can't seem to get the optional and working.
我希望用户能够输入一系列关键字,并在它们之间选择“AND”,但我似乎无法获得可选和工作。 It always expects it, even though I've marked it with a ?
它总是期待它,即使我用它标记它? (zero or one).
(零或一)。
Paste this grammar into http://pegjs.majda.cz/online : 将此语法粘贴到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]
My goal is to have either of these inputs parse into an array of ["foo", "bar"]: 我的目标是让这些输入中的任何一个解析为[“foo”,“bar”]的数组:
foo bar
foo and bar
Ok, nevermind. 好吧,那算了。 I figured it out.
我想到了。 It was because I made the optional whitespace preceding the 'and' as part of the and rule, so it expected the rest of the rule.
这是因为我做了一个可选的空格前的“和”的部分和规则,因此,预计该规则的其余部分。 I just needed to move it out, into the pair rule, like so:
我只需将它移出,然后进入配对规则,就像这样:
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]
Here is my answer: 这是我的答案:
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]+
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: 您可以使用以下字符串来尝试https://pegjs.org/online :
carlos, peter, vincent, thomas, and shirly
Hope it helps someone. 希望它可以帮助某人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.