我正在用Java編寫一個應用程序,顯示文件名中的第一個單詞與用戶定義的字符串相匹配的文件列表,然後根據一些首選項刪除或重新排列它們。我目前正處於尋找找到我的文件的好方法的階段。使用this Java Tutorial我結束了這樣的事情:Java正則表達式和PathMatcher
Path source = Paths.get(sourceText.getText());
Path dest = Paths.get(destText.getText());
System.out.println("Source:" + source.toString());
System.out.println("P/N: " + partNoText.getText());
String matchString = "glob:**" + partNoText.getText() + "*";
System.out.println("Matching: " + matchString);
fileFinder = new FileFinder(matchString);
try {
Files.walkFileTree(source, fileFinder);
} catch (IOException e1) {
e1.printStackTrace();
}
for (Path path : fileFinder.getResult()) {
System.out.println("Moving: " + path.getFileName());
Path target = Paths.get(dest.toString() + "\\" + path.getFileName());
try {
Files.move(path, target, REPLACE_EXISTING);
} catch (IOException e1) {
e1.printStackTrace();
}
}
其中FileFinder延伸SimpleFileVisitor並擁有本visitFile方法:
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
System.out.println(file.toString());
System.out.println(fileMatcher.matches(file));
if (fileMatcher.matches(file)) {
result.add(file);
return FileVisitResult.CONTINUE;
}
return FileVisitResult.CONTINUE;
}
我對這個問題的是,水珠會拿起任何文件,其中文件名包含零件編號。以任何方式。所以如果我的文件被稱爲「12345 RevA真的很大的第二部分:電動Bugaloo」,那麼如果用戶輸入「1」或「123」或「Bugaloo」,字符串就會匹配。理想情況下,只有當用戶輸入「12345」時纔會匹配。
我試着將我的matchString切換爲"regex: .*" + partNoText + "\\b"
,它適用於從this other Java Tutorial修改過的正則表達式測試工具。我究竟做錯了什麼? PathMatcher
的工作方式與常規的Matcher
不同嗎?
P.S.任何具有「Text」字樣的變量,如sourceText
和partNoText
都是JTextFields。 Hopefull是代碼的唯一部分,大部分內容都不清楚。
文件名_globbing_是_ **不是** _正則表達式; globbing比正則表達式更受限制。另外,作爲一個glob的'foo *'匹配foo-with-anything-after,相當於一個正則表達式將是'foo。*'= foo,後跟任意一個char'.'零次或多次''''' –
_「理想情況下,只有當用戶輸入」12345「時纔會匹配。」_ _部件號_always_是文件名的第一部分嗎?所有零件號碼都是_exactly_ 5位數字嗎?零件號碼_always_後跟一個空格?有一個精確的定義可以幫助你找到一個好的正則表達式。我不認爲globbing會在這種情況下做到這一點,儘管你可以通過glob來減少匹配空間,然後正則表達式匹配globbing找到的東西。 –
@StephenP對於你的第一個評論,我的理解是globbing和regex是兩種不同的方法,可以創建廣義字符串來匹配。你可以從我的問題的底部看到,我決定從globbing改爲正則表達式由於其侷限性 –