我正在尝试提出一个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种情况的假.我哪里错了?
干杯,唐
public boolean isFilename(String filename) {
int i=filename.lastInstanceOf(".");
return(i != -1 && i != filename.length - 1)
}
Run Code Online (Sandbox Code Playgroud)
会更快,无论你做什么,把它放在一个方法将更具可读性.
| 归档时间: |
|
| 查看次数: |
11568 次 |
| 最近记录: |