Java Matcher:如何用一个正则表达式匹配多行



我的方法获取一个文件,并尝试提取标题###Title###和结束###---###之间的文本。我需要它来提取多条线,并将每条线放入一个数组中。但由于readAllLines()将所有行转换为一个数组,我不知道如何比较和匹配它

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
###---###

输出显示"没有匹配项。">而不是条目。

您不需要regex。只要在数组中循环并逐行比较项目,在开始和结束标记之间进行比较就足够了。

ArrayList<String> input = (ArrayList<String>) Files.readAllLines(f.toPath(), StandardCharsets.US_ASCII);
ArrayList<String> output = new ArrayList<String>();
boolean matched = false;
for (String line : input) {
if (line.equals("###---###") && matched) matched = false; //needed parentheses
if (matched) output.add(line);
if (line.equals("###Test File###") && !matched) matched = true;
}

根据您的评论,如果它们与发布的方式相同,那么我认为regex不需要满足此要求。您可以逐行读取并进行"###"的包含

public static void main(String args[])
{
ArrayList<String> dataList = new ArrayList<String>();
try{
// Open the file that is the first 
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)   {
// this line will skip the header and footer with '###'
if(!strLine.contains("###");
dataList.add(strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
//Now dataList has all the data between ###Test File### and ###---###
}

您还可以根据忽略行的要求更改contains方法参数

最新更新