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

标签 java regex 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
###---###

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

最佳答案

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

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/

相关文章:

java - 将 C# 正则表达式转换为 Java 匹配器问题

java - Java 8 是否存在一些方便的方式来增加对象的属性?

java - com.itextpdf.text.exceptions.InvalidPdfException : Rebuild failed: Error reading string at file pointer

Python正则表达式nltk网站提取

c# - 正则表达式。仅替换正则表达式的一部分

java - 在java中,当使用正则表达式查找模式时,如何获得嵌套结果?

java - 由于JDK功能不受支持,Jenkins Maven编译失败?

java - 当接口(interface) A 在其方法签名中定义接口(interface) B 时

php - Regex Youtube-将自动播放设置为0(特定视频哈希除外)

java - 如何从字符串中提取以下模式?