【发布时间】:2019-12-08 02:19:04
【问题描述】:
由于某种原因,当我希望我的代码仅打印出与我的正则表达式模式不匹配的文件时,我的代码将打印所有文件。我需要它来打印出与模式不匹配的文件,因为我不知道所有文件命名中可能存在不一致。 MY regex 表示可以标记文件名的正确可能性。我在 regex101 上检查了我的正则表达式模式,它是正确的。我不是程序员,但我是一名从事海量数据库工作的心理学学生。
我尝试将 Pattern 变成一个列表模式,我尝试将 patternList.matcher(file.getName()) 放入它自己的 Matcher 变量中。
private static void checkFolder(File root, Pattern patternList) {
for(File file : root.listFiles())
if(file.isFile()){
if(patternList.matcher(file.getName()).matches())
checkFolder(rootFolder, patternList);
else
System.out.println(file); //print if it does not match
}
例如,如果我的代码查看这些文件名:
- 95F前怒.BW
- 95F.Front.Anger.C.Micro
- 95F.Front.Fear.C.Micro
- 95F.Front.Frown.BW
我的正则表达式是这样的:
Pattern patternList = Pattern.compile("((\\d{1,3}(F|M)\\.(Front|Profile|Right)"
+"\\.(Anger|Fear|Frown|Smile)\\.(BW\\.Micro|BW|C\\.Micro|C)))|"
+"(\\d{1,3}(F|M)\\.(Front|Profile|Right)\\.(Neutral|Smile)\\."
+"(C\\.Micro|C|BW\\.Micro|BW|HighLight|LowLight|MedLight)\\.(BW\\.Micro|BW|C\\.Micro|C))|"
+"(\\d{1,3}(F|M)\\.(Selfie1|Selfie2|StudentID)\\.(C\\.Micro|C|BW\\.Micro|BW))");
我的代码应该只打印出 95F Front Anger.BW,因为它有空格而不是点,但我的代码仍然会打印出所有四个文件名。
我也试过这样做:
private static void checkFolder(File root, Pattern patternList) {
for(File file : root.listFiles())
if(file.isFile()){
if(!patternList.matcher(file.getName()).matches())
{
System.out.println(file); //print the file that doesnt match the regex
}
else
{
checkFolder(rootFolder, patternList);
}
}
}
【问题讨论】:
-
哦,您缺少布尔值,只需在末尾添加
.matches()。哦,你有那个.. -
yeahhhhhhhhhh,我不确定是 for 循环还是 if 语句的问题
-
你可以试着把它拆开
Matcher m = patternList.matcher();然后if ( m.matches() )但是.. -
什么是
rootFolder?您是否打算尝试使用file进行递归调用?如果是这样,你应该只尝试file.isDirectory()。 -
是的,我已经尝试将其分解:/