简体   繁体   English

如果正则表达式模式在Java中匹配,则提取文件的下一行数据

[英]Extracting the next line data of a file if regex pattern matches in Java

I want to extract the next line data of a text file if regex pattern matches in Java. 如果正则表达式模式在Java中匹配,我想提取文本文件的下一行数据。 I am able to detect and match the pattern data in a text file, But unable to print the next line of pattern data. 我能够检测并匹配文本文件中的模式数据,但无法打印下一行模式数据。

Test data: 测试数据:

*** Explorer
GenV Deno Znet

Regular Expression for matching the Explorer 用于匹配Explorer的正则表达式

[*\\+]+[\\s+]+[Explorer]+[:]

Kindly help me on how to get the next line if *** Explorer pattern is found. 如果找到*** Explorer模式,请帮助我如何获得下一行。

You can use this regex with a capturing group for the next line after your search pattern: 您可以将此正则表达式与捕获组一起用于搜索模式之后的下一行:

[*]+\s+Explorer\R(.*)

Next line is captured in group #1 在#1组中捕获下一行

Regex Breakup: 正则表达分手:

  • [*]+\\s+Explorer - Match your search pattern [*]+\\s+Explorer - 匹配您的搜索模式
  • \\R - Match any newline character \\R - 匹配任何换行符
  • (.*) - Match and captured full line in group #1 (.*) - 在组#1中匹配并捕获整行

In Java use: 在Java中使用:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "[*]+\\s+Explorer\\R(.*)";
final String input = "*** Explorer\nGenV Deno Znet";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(input);

while (matcher.find()) {
    System.out.println("match: " + matcher.group(1));
}

RegEx Demo RegEx演示

You can Use: 您可以使用:

[*\s]+Explorer\n(.*?)$

在此输入图像描述

Regex Demo 正则表达式演示

Well, for starters the regex is not going to match "*** Explorer" 那么,对于初学者来说,正则表达式不会匹配“*** Explorer”

It will match "*** Explorer:" 它将匹配“*** Explorer:”

If this is java, can't you just read the next line? 如果这是java,你不能只读下一行吗?

        while ((lineText = lineReader.readLine()) != null) {
            hasMatch = lineText.matches(regex);
            if(hasMatch) {
                lineText = lineReader.readLine();
                System.out.println(lineText);
            }
        }

Works for me. 适合我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM