这是我使用正则表达式为FileFilter编写的一些代码。目的是匹配上载的日志文件并增加文件名的索引。我不想担心文件名中的任何内容,而只是将其作为字符串文字接受,而无需仔细研究对正则表达式模式匹配有意义的文件名转义字符。
mylog.log
mylog-1.log
mylog-2.log
public boolean accept(File file) {
Pattern pattern = Pattern.compile(filenameWithoutExtension + "-*[0-9]*." + extension);
Matcher matcher = pattern.matcher(file.getName());
return matcher.matches();
}
我的问题是,如果文件名包含括号,则该命令将不起作用,因为括号意味着模式匹配器有一些特殊之处。
mylog(copy).log
我想用一种表示法将filenameWithoutExtension括起来,匹配此字符串,而忽略其中可能是模式匹配语法的任何内容。
最佳答案