gpt4 book ai didi

Java匹配器: How to match multiple lines with one regex

转载 作者:行者123 更新时间:2023-12-01 17:17:54 25 4
gpt4 key购买 nike

我的方法采用一个文件,并尝试提取标题 ###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
###---###

输出显示“没有匹配项。”而不是条目。

最佳答案

你不需要正则表达式。循环遍历数组并逐行比较项目就足够了,将这些项目放在开始标签和结束标签之间。

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;
}

关于Java匹配器: How to match multiple lines with one regex,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20736288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com