Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java正则表达式与路径_Java_Regex_Path - Fatal编程技术网

Java正则表达式与路径

Java正则表达式与路径,java,regex,path,Java,Regex,Path,我知道还有其他问题,但即使有这些问题,我也找不到代码中的错误。 我写这篇文章是为了检查我的文本字段中写的内容是否是路径,但它似乎不正确。代码如下: textFieldNewGameUrl.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent arg0) { boolean isMatched = (textFieldNewGa

我知道还有其他问题,但即使有这些问题,我也找不到代码中的错误。 我写这篇文章是为了检查我的文本字段中写的内容是否是路径,但它似乎不正确。代码如下:

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.");
            }

        }
    });

编写正则表达式来检查路径相当复杂

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

您的模式没有完全被破坏,但您需要它以反斜杠开始。相对路径不需要这样做

什么是预期的输入和行为?什么是“不正确”意味着什么?所以您要检查windows路径的正确性。在您看来,仅包含“NUL”的路径有效吗?另见。换言之;只要试着打开文件,看看会发生什么。别忘了,
.matches()
会尝试并检查整个输入是否与regex匹配,而不像它的名称所暗示的那样。此外,您的正则表达式非常合适,您应该为它创建一个
模式。我可以将textField设置为不可编辑,但我更愿意设置为不可编辑。这段代码的输出总是“奇怪的事情发生了:检查路径”。因为isMarched总是false。我更改了创建模式的代码,我使用pattern.compile(..)方法和matcher m。。但是m.matches()仍然是错误的。我更新了问题中的代码