Java正则表达式与路径

时间:2014-03-30 10:30:35

标签: java regex path

我知道还有其他问题,但即使有这些问题,我也无法在代码中找到错误。 我写这个是为了检查我的textField中写的是一个路径,但它似乎是不正确的。代码如下:

textFieldNewGameUrl.addFocusListener(new FocusAdapter() {   
        @Override
        public void focusLost(FocusEvent arg0) {

            boolean isMatched = (textFieldNewGameUrl.getText()).matches("([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?");

            if(isMatched){          
                labelNewGameFeedback.setText("Ok, the path is correct");
            }
            else{
                labelNewGameFeedback.setText("Strange things have happened : check the path.");
            }

        }
    });

1 个答案:

答案 0 :(得分:0)

将Regex写入Check Paths非常复杂。

public static void main(String[] args) {
   Pattern pattern = Pattern.compile("([a-zA-Z]:)?(\\\\[a-zA-Z0-9_.-]+)+\\\\?");
   System.out.println(pattern.matcher("D:\\").matches());
   System.out.println(pattern.matcher("D:\\A").matches());
   System.out.println(pattern.matcher("A\\B").matches());
   System.out.println(pattern.matcher("\\A\\B").matches());
}

这将输出

false 
true 
false 
true

您的模式并未完全破坏,但您需要以反斜杠开头。相对路径不需要这样做。