Java文件扩展名正则表达式

Dón*_*nal 4 java regex

我正在尝试提出一个Java正则表达式,只有当它具有有效的扩展名时才匹配文件名.例如,它应匹配"foo.bar"和"foo.b",但不是"foo".也不是"foo".

我写了以下测试程序

public static void main(String[] args) {
  Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z");

  boolean one = fileExtensionPattern.matcher("foo.bar").matches();
  boolean two = fileExtensionPattern.matcher("foo.b").matches();
  boolean three = fileExtensionPattern.matcher("foo.").matches();
  boolean four = fileExtensionPattern.matcher("foo").matches();

  System.out.println(one + " " + two + " " + three + " " + four);
}
Run Code Online (Sandbox Code Playgroud)

我希望这会打印"true true false false",但是它会打印出所有4种情况的假.我哪里错了?

干杯,唐

Ada*_*eld 10

所述Matcher.matches()函数尝试匹配针对整个输入的模式.因此,您必须添加.*到正则表达式的开头(并且\\Z最后也是多余的),或使用find()方法.


Bil*_*l K 8

public boolean isFilename(String filename) {
    int i=filename.lastInstanceOf(".");
    return(i != -1 && i != filename.length - 1)
}
Run Code Online (Sandbox Code Playgroud)

会更快,无论你做什么,把它放在一个方法将更具可读性.