java - 捕获多行字符组

标签 java regex multiline

正则表达式专业人士,我有一个 GoogleTest --gtest_list_tests 输出,我需要解析它以获取每个测试套件和案例。输出具有以下格式:

TestSuite1.  
    TestCase1  
    TestCase2  
TestSuite2.  
    TestCase1  
    TestCase2  
    TestCase3  

等等。我需要一个 java 正则表达式模式来捕获每个测试套件及其案例。对于上述输入,我需要将组 1 设置为

TestSuite1.  
    TestCase1  
    TestCase2  

第 2 组为

TestSuite2.  
    TestCase1
    TestCase2  
    TestCase3  

我似乎不知道如何让它发挥作用。现在我正在使用这种模式:

(.+\\.\\n(?:\\s+.+\\n)+)+ 

这不起作用。谢谢

最佳答案

如果设置多行标志,则可以使用行终止符$:

public static void main(String[] args)
    throws IOException
{
    String s = "TestSuite1.\n" + 
               "    TestCase1\n" + 
               "    TestCase2\n" + 
               "TestSuite2.\n" + 
               "    TestCase1\n" + 
               "    TestCase2\n" + 
               "    TestCase3";

    Matcher matcher = Pattern.compile("\\w+\\.$(\\s+\\w+$)+", Pattern.MULTILINE).matcher(s);

    while (matcher.find())
    {
        System.out.println(matcher.group());
        System.out.println("-----------");
    }
}

Output:

TestSuite1.
    TestCase1
    TestCase2
-----------
TestSuite2.
    TestCase1
    TestCase2
    TestCase3
-----------

关于java - 捕获多行字符组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48890026/

相关文章:

java - 我是否应该将返回类型重命名为更通用的名称以便重用它?

javascript - 查找两个字符串值中单词的常见出现次数

asp.net - 多行 TextBox 多个换行符

python - python中的多行字符串格式

html - 正则表达式抓取表单标签内容不起作用

java - SomeClass.<OtherClass>someMethod() 语法含义

java - 如何将MySQL数据库中的图像显示到java中的jTable中?

java - Spring API : the program is not finding the pat into the controller

PHP URL 正则表达式和参数

正则表达式在文件中搜索一组括号,其中包含八个字符,全部为 1 或 0,至少有一个 1?