出于某种原因,我的代码将在我希望它仅打印出不符合我的正则图案的文件时打印所有文件..我需要它来打印出与不匹配的文件该模式是因为我不知道文件命名中存在的所有可能存在。我的正则是可以标记文件名的正确可能性。我在Regex101上检查了我的正则图案,这是正确的。我不是编码员,但我是一名心理学专业的学生。
ive尝试将模式制作到列表模式中,然后我尝试将patternlist.matcher(file.getName(((放入自己的匹配器变量。
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前愤怒。
我也尝试这样做:
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);
}
}
}
无法复制。这是一个最小的,可重现的示例:
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))");
String[] tests = { "95F Front Anger.BW",
"95F.Front.Anger.C.Micro",
"95F.Front.Fear.C.Micro",
"95F.Front.Frown.BW" };
for (String s : tests)
System.out.printf("%-7s %s%n", patternList.matcher(s).matches(), s);
输出
false 95F Front Anger.BW
true 95F.Front.Anger.C.Micro
true 95F.Front.Fear.C.Micro
true 95F.Front.Frown.BW
它与您想要的方式匹配。
也许file.getName()
不会返回您认为的作用。