我正在尝试设置一个接受有效文件名的程序:
" File.pdf" - 有效
" File..pdf" - 无效(或更多点数/周期)
" .PDF" - 无效
" File.Drop.pdf" - 无效
这是我到目前为止所做的:
if (name.equals(("^\\b([a-zA-Z]+\\.+)\\b$"))){
this.name = name;
}
我知道我在这里做错了什么,但任何帮助都会非常感激。提前谢谢。
答案 0 :(得分:1)
正确的表达方式是:
if (name.matches("^\\w+\\.\\w+$")) {
this.name = name;
}
答案 1 :(得分:1)
这里有一些解决方案:
1- Guava的CharMatcher API非常强大和简洁:
CharMatcher.is('.').countIn("test.pdf"); //returns 1
2 - 计算字符串之间的差异有.
或不是
String string = "test.pdf";
int count = string.length() - string.replaceAll("\\.", "").length();
3 - 尝试使用Apache Commons' StringUtils:
int count = StringUtils.countMatches("test.pdf", '.');
4 - 使用正则表达式:
String str = "test.pdf";
Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(str);
System.out.println(str);
int count = 0;
while (m.find()) {
if(str.charAt(m.start())=='.') count++;
}
System.out.println(count); // will print 1