简体   繁体   English

骰子符号(递归下降解析实现):没有分隔符的扫描器

[英]Dice notation (recursive descent parsing implementation): a scanner without delimiter

I would like to build a recursive descent parsing implementation of the dice notation using the java Scanner if possible. 如果可能的话,我想使用java Scanner构建一个骰子表示法的递归下降解析实现。 I've previously opened a question about it , but it seemed that I had my requirements way too simplified. 我之前已经开了一个关于它的问题 ,但似乎我的要求太简单了。 So I'm presenting here the request in its globality. 所以我在这里提出它的全局性请求。

I really hope that this is feasible with the class java.util.Scanner, but if needed I will write my own scanner. 我真的希望使用类java.util.Scanner这是可行的,但如果需要,我会编写自己的扫描程序。 I would like to avoid this one right now. 我现在想避免这个。

 expression   =  { whitespace } , [ plusminus ] , roll , { plusminus , ( roll | number , { whitespace } ) } ;
 roll         =  [ number ] , ( "d" | "D" ) , ( number | "%") , [ "-" ( "L" | "H" ) ] , { whitespace } ;
 plusminus    =  ( "+" | "-" ) , { whitespace } ;
 number       =  nonzerodigit , { digit } ;
 digit        =  nonzero digit | "0" ;
 nonzerodigit =  "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
 whitespace   =  ? Java definition of a whitespace ? ;

So in fact, I've tried to write the following code: 所以实际上,我已经尝试编写以下代码:

 Scanner s = new Scanner("1d6");
 if (s.hasNextInt()) {
  s.nextInt();
 } else {
  throw new java.text.ParseException();
 }

But obviously it keeps failing. 但显然它一直在失败。

Also as suggested in the previous question, I've tried the findWithinHorizon methods but it really finds the next pattern and doesn't check from where I am. 同样如前一个问题所示,我已经尝试了findWithinHorizo​​n方法,但它确实找到了下一个模式,并没有检查我的位置。 So I can't "pushback" the string if it is not what I need... 如果它不是我需要的话,我不能“推回”字符串...

So any suggestion on how I should use java.util.Scanner in this context? 那么关于如何在这种情况下使用java.util.Scanner的任何建议呢? Or maybe I have to write my own scanner? 或许我必须自己编写扫描仪?

You should not use java.util.Scanner. 你不应该使用java.util.Scanner。 Take a look at the design of JParsec . 看看JParsec的设计。

For working with grammars, you should use ANTLR . 对于使用语法,您应该使用ANTLR It's a parser generator. 它是一个解析器生成器。 From your grammar, you'll be able to generate easily a parser, and use this class to parse your expression. 从您的语法中,您将能够轻松生成解析器,并使用此类来解析您的表达式。

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

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