递归命令解析器,用于解决重复语句

时间:2015-06-24 16:09:20

标签: java parsing syntax

我正在构建一个识别简单命令的解析器,例如“DOWN。”,“UP”。和“REP 3.”。它必须能够相当自由地解析命令。写

应该是合法的
"DOWN % asdf asdf asdf
."

其中%表示注释,而fullstop表示命令结尾。这个续站可以在下一行。

到目前为止,这一切都很好,但我正在与Rep部分挣扎(代表重复。) 我应该能够发出如下命令:

DOWN .DOWN. REP 3 " DOWN. DOWN. 
  DOWN   . % hello this is a comment
  REP 2 " DOWN. ""

这应该给我 17 DOWNS 。重复的语义如下:REP x“commands”其中x是重复引号内列出的命令的次数。注意REP可以嵌套在REP中。以下代码用于处理DOWN命令。传入的文本从 System.in 文本文件中读取。

    public void repeat(String workingString) {

    if (workingString.matches(tokens)) {
        if (workingString.matches("REP")) {
            repada();
        } else
        if (workingString.matches("(DOWN).*")) {
            String job = workingString.substring(4);
            job = job.trim();
            if (job.equals("")) {
                String temp= sc.next();
                temp= temp.trim();

                // Word after DOWN.
                if (temp.matches("\\.")) {
                    leo.down()
                    // If word after DOWN is a comment %
                } else if (temp.matches("%.*")) {
                    boolean t = comment();
                } else {
                    throw SyntaxError();
                }
            } else if (job.matches("\\..*")) {
                workingString += job;
                System.out.println("Confirm DOWN with .");
            }

        } else if (workingString.matches("\\.")) {
            instructions += workingString;
            System.out.println("Fullstop");
        } else if (workingString.matches("%.*")) {
            comment();
        } else {
            // work = sc.next();
            work = work.trim().toUpperCase();
            System.out.println(work);
        }
    } else {
        System.out.println("No such token: " + workingString);
    }
}

我在重复功能上开始了工作:

public String repada(){
        String times = sc.next();
        times.trim();
        if (times.matches("%.*")) {
            comment();
            times = sc.next();
        }
        String quote = sc.next();
        quote.trim();
        if(quote.matches("%.*")){
            comment();
            quote = sc.next();
        }
        String repeater = "";
        System.out.println("REP " + times + " "+quote);}

但是我认为我的整个系统可能需要返工。关于如何更轻松地解决这个问题的任何建议将不胜感激!

0 个答案:

没有答案