我對使用正則運算式很陌生,所以我當前的代碼有問題。我創建了一個回傳檔案串列的抽象檔案搜索。我希望這個搜索器被正則運算式過濾(例如,它基于正則運算式過濾器查找的擴展名)。
我的抽象搜索器的代碼:
public abstract class AbstractFileDiscoverer implements IDiscoverer {
private final Path rootPath;
AbstractFileDiscoverer(final Path rootPath) {
super();
this.rootPath = rootPath;
}
protected List<File> findFiles() throws IOException {
if (!Files.isDirectory(this.rootPath)) {
throw new IllegalArgumentException("Path must be a directory");
}
List<File> result;
try (Stream<Path> walk = Files.walk(this.rootPath)) {
result = walk.filter(p -> !Files.isDirectory(p)).map(p -> p.toFile())
.filter(f -> f.toString().toLowerCase().endsWith("")).collect(Collectors.toList());
}
return result;
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
}
我希望正則運算式過濾以下部分,以便只收集正則運算式回傳為 true 的檔案(對于 .bat 和 .sql 檔案)。
result = walk.filter(p -> !Files.isDirectory(p)).map(p -> p.toFile())
.filter(f -> f.toString().toLowerCase().endsWith("")).collect(Collectors.toList());
誰能幫我實作它?
第一次編輯:我知道toString().toLowerCase().endsWith("")總是回傳true,我實際上需要正則運算式而不是帶有擴展名的字串。我忘了提那個。
uj5u.com熱心網友回復:
試試這個網站:https ://regexr.com/并粘貼正則運算式. (?:.sql|.bat)$以獲得解釋。
在代碼中它看起來像這樣:
Stream.of("file1.json", "init.bat", "init.sql", "file2.txt")
.filter(filename -> filename.matches(". (?:.sql|.bat)$"))
.forEach(System.out::println);
uj5u.com熱心網友回復:
Jamie Zawinski 有一句名言,關于當更簡單的非正則運算式代碼可以使用正則運算式時。
在您的情況下,我會避免使用正則運算式,而只會撰寫一個私有方法:
private static boolean hasMatchingExtension(Path path) {
String filename = path.toString().toLowerCase();
return filename.endsWith(".bat") || filename.endsWith(".sql");
}
然后你可以在你的流中使用它:
result = walk.filter(p -> !Files.isDirectory(p)).
.filter(p -> hasMatchingExtension(p))
.map(p -> p.toFile())
.collect(Collectors.toList());
(考慮回傳List<Path>。Path 類是 File 類的現代替代品,其中一些實際操作檔案的方法存在設計問題。)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/473924.html
上一篇:如何將空格替換為字串中的亂數
下一篇:如何調節中弦
