java文件名过滤模式 [英] java filenames filter pattern
问题描述
我需要实现
File[] files = getFiles( String folderName, String ptrn );
其中ptrn是* 2010 * .txt的命令提示符样式模式
Where ptrn is a command prompt style pattern like "*2010*.txt"
我喜欢FilenameFilter类,但不能实现
public boolean accept(File dir,String filename)
因为String.matches()不接受这样的模式。
I'm familar with FilenameFilter class, but can't implement
public boolean accept(File dir, String filename)
because String.matches() doesn't accept such patterns.
谢谢!
推荐答案
The String#matches()
accepts regular expression patterns.
外行人变体 * * * * .txt
的正则表达式将为。* 2010. * \.txt
。
The regex variant of the "layman's" variant *2010*.txt
would be .*2010.*\.txt
.
所以以下内容应该有效:
So the following should work:
public boolean accept(File dir, String name) {
return name.matches(".*2010.*\\.txt");
}
双反斜杠只是代表一个实际的反斜杠,因为反斜杠本身是Java的 String
中的转义字符。
The double backslash is just there to represent an actual backslash because the backslash itself is an escape character in Java's String
.
或者,您也可以使用其他 String
方法:
Alternatively, you can also do it without regex using the other String
methods:
public boolean accept(File dir, String name) {
return name.contains("2010") && name.endsWith(".txt");
}
你最好的赌注可能会让 ptrn
代表一个真正的正则表达式模式,或者使用
\。$来替换每个
。
c $ c>和 *
与。*
,以便它成为一个有效的正则表达式模式。
Your best bet is likely to let ptrn
represent a real regex pattern or to string-replace every .
with \.
and *
with .*
so that it becomes a valid regex pattern.
public boolean accept(File dir, String name) {
return name.matches(ptrn.replace(".", "\\.").replace("*", ".*"));
}
这篇关于java文件名过滤模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!