Java正则表达式无法验证

时间:2015-08-08 17:36:20

标签: java regex

所以我一直试图做一个简单的java语法检查器。我使用正则表达式来检查textarea(代码)上写的每一行,看看它是否写得正确。我遇到的问题是正则表达式无法正确验证它,当它正确时(代码写得正确),它会将其验证为False(代码错误)。所以我不知道这个问题是我的正则表达还是我做错了。

如果有人可以帮助我,我会非常感激。感谢

代码我正在使用:

    String codeText = codeTxt.getText().trim(); //Code from textarea
    String errors   = ""; //Saves the errors from the code
    int openBrace   = 0;  //Check if we open a curly brace.

    //Break lines by new line.
    String lines[] = codeText.split("\\r?\\n");

    //Regular Expresiona
    String libraries = "(import) (javax)\\.([a-zA-Z0-9]+)(\\.\\*;)",
           classCheck = "(public|private) class ([a-zA-Z]+) (extends ([a-zA-Z]+))?\\{";

    //If first line is an import
    if(lines[0].matches(libraries) == false){
        errors += "- Error on line: " + String.valueOf(1) + " - " + lines[0] + "\n";
    }

    //Check rest of lines
    for(int i = 1; i < lines.length; i++){

        if(lines[i].matches(classCheck) == false && lines[i].equals("") == false){
           errors += "- Error on line: " + String.valueOf(i + 1) + " - " + lines[i] + "\n";

        }else if(lines[i].matches(classCheck) == true && lines[i].equals("") == false){
            openBrace++; //Indicates how many curly braces are opened.

        }

    }

    //Print errors
    if(errors.equals("")){
        consoleTxt.setText("Correct syntax.");
    }else{
        consoleTxt.setText(errors);
    }

0 个答案:

没有答案