Java regex选择特定的多行

Java regex选择特定的多行,java,regex,Java,Regex,我试图在一个特定的术语之后从大量的行(高达100到130)中捕获一组行 这是我的密码 String inp = "Welcome!\n" +" Welcome to the Apache ActiveMQ Console of localhost (ID:InternetXXX022-45298-5447895412354475-2:9) \n" +" You can find more information about Apa

我试图在一个特定的术语之后从大量的行(高达100到130)中捕获一组行

这是我的密码

String inp = "Welcome!\n"
                +" Welcome to the Apache ActiveMQ Console of localhost (ID:InternetXXX022-45298-5447895412354475-2:9) \n"
                +"  You can find more information about Apache ActiveMQ on the Apache ActiveMQ Site \n"
                +" Broker\n"
                +" Name localhost\n"
                +" Version  5.13.3\n"
                +" ID   ID:InternetXXX022-45298-5447895412354475-2:9\n"
                +" Uptime   14 days 14 hours\n"
                +" Store percent used   19\n"
                +" Memory percent used  0\n"
                +" Temp percent used    0\n"
                + "Queue Views\n"
                + "Graph\n"
                + "Topic Views\n"
                + "  \n"
                + "Subscribers Views\n";
        Pattern rgx = Pattern.compile("(?<=Broker)\n((?:.*\n){1,7})", Pattern.DOTALL);
        Matcher mtch = rgx.matcher(inp);
        if (mtch.find()) {
            String result = mtch.group();
            System.out.println(result);
        }
但是我的代码在“Broker”之后给了我所有的行。我能知道我做错了什么吗


其次,我想了解,“:表示非捕获组,但为什么我的正则表达式((?:.*\n))能够在代理之后捕获行?

您必须删除
模式。DOTALL
,因为它使
也匹配新行,并且您使用
*
捕获整个文本,因此不需要限制量词

此外,您的真实数据似乎包含CRLF行尾,因此使用
\R
比使用
\n
来匹配换行符更方便。否则,您可以使用(或其嵌入的等效标志,
(?d)
,在模式内),然后您可以保持模式不变(因为只有
\n
,LF将被视为换行符,
将匹配回车符,CRs)

另外,我建议
trim
ming
结果

使用


Pattern rgx=Pattern.compile(“(?请不要在变量(inp、rgx、mtch)中使用俚语或短词),只需编写它即可out@WiktorStribiżew,尝试过,但仍然是相同的结果…!你看到了吗?@WiktorStribiżew,是的…但是当我在eclipse中运行时,它向我展示了所有的东西。。?
Name    localhost\n
Version 5.13.3\n
ID  ID:InternetXXX022-45298-5447895412354475-2:9\n
Uptime  14 days 14 hours\n
Store percent used  19\n
Memory percent used 0\n
Temp percent used   0\n
Pattern rgx = Pattern.compile("(?<=Broker)\\R((?:.*\\R){1,7})");
// Or, 
// Pattern rgx = Pattern.compile("(?d)(?<=Broker)\n((?:.*\n){1,7})");
Matcher mtch = rgx.matcher(inp);
if (mtch.find()) {
    String result = mtch.group();
    System.out.println(result.trim());
}