我的方法需要一個文件,並試圖提取報頭###Title###
和關閉###---###
之間的文本。我需要它提取多行並將每行放入數組中。但由於readAllLines()
將所有行轉換爲數組,我不知道如何比較和匹配它。Java匹配器:如何匹配多個行與一個正則表達式
public static ArrayList<String> getData(File f, String title) throws IOException {
ArrayList<String> input = (ArrayList<String>) Files.readAllLines(f.toPath(), StandardCharsets.US_ASCII);
ArrayList<String> output = new ArrayList<String>();
//String? readLines = somehow make it possible to match
System.out.println("Checking entry.");
Pattern p = Pattern.compile("###" + title + "###(.*)###---###", Pattern.DOTALL);
Matcher m = p.matcher(readLines);
if (m.matches()) {
m.matches();
String matched = m.group(1);
System.out.println("Contents: " + matched);
String[] array = matched.split("\n");
ArrayList<String> array2 = new ArrayList<String>();
for (String j:array) {
array2.add(j);
}
output = array2;
} else {
System.out.println("No matches.");
}
return output;
}
這是我的文件,我100%確定編譯器正在讀取正確的文件。
###Test File###
Entry 1
Entry 2
Data 1
Data 2
Test 1
Test 2
###---###
輸出說「沒有匹配」。而不是條目。
你的問題到底是什麼? –
所有這些都是在一行還是在圖片中? – Keerthivasan
@ PM77-1我如何讓它匹配而不是返回「不匹配」。方法? –