简体   繁体   English

如何解析以相同字符开头的简约选项

[英]How to parse alternatives in parsimonious that start with same characters

I'm using parsimonious to do some parsing and I'm having trouble figuring out how to properly parse alternatives that share the first character in an unordered away: 我正在使用简约来进行一些解析,我无法弄清楚如何正确地解析在无序中共享第一个字符的替代方案:

For example: 例如:

Text: 文本:

2 > 3
2 >= 3

Grammar: 语法:

expr = ~"[0-9]+" space operator space ~"[0-9]+"
operator = ">" / "==" / "<" / ">=" / "<="
space = ~"[\\s]*"

The first line of the text will parse correctly, but the second line won't. 文本的第一行将正确解析,但第二行不会。 It seems like it matches ">" then gets stuck since it sees a "=". 似乎它匹配“>”然后卡住,因为它看到“=”。 It never matches ">=" as a whole. 它永远不会匹配“> =”作为一个整体。 How do I make it do that without having to specify these in careful order? 如何做到这一点,而不必仔细指定这些? I tried using "&" for lookahead matching but that doesn't seem to work. 我尝试使用“&”进行超前匹配,但这似乎不起作用。

parsimonious is based on PEGs. 简约基于PEG。 One of the distinguished properties of PEGs is that alternative operator is ordered, ie alternative choices are always tried from left to right and the first successful match wins. PEG的一个显着特性是订购替代运营商,即总是从左到右尝试替代选择,并且第一次成功匹配获胜。 Thus, PEG grammars are never ambiguous but you must be aware of this property when writing your grammar and order alternatives accordingly. 因此,PEG语法永远不会含糊不清,但在编写语法和相应的订购备选方案时,您必须了解此属性。 PEGs are actually a specifications of recursive descent parsers. PEG实际上是递归下降解析器的规范。

In your case you should really reorder matches in operator production so that >= is tried first. 在您的情况下,您应该在operator生成中重新排序匹配,以便首先尝试>= The other solution would be to prevent > match to be successful if followed by = . 另一个解决方案是如果后跟= ,则阻止>匹配成功。 This is achieved using syntactic predicate Not . 这是使用语法谓词Not实现的。 In parsimonious it is denoted with ! 在简约中用它来表示! , so this should work also: operator = ">" !"=" / "==" / "<" / ">=" / "<=" This applies generally to all PEG parsers. ,所以这也应该起作用: operator = ">" !"=" / "==" / "<" / ">=" / "<="这通常适用于所有PEG解析器。 It is not parsimonious specific. 它不是特定的简约。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM