Java 捕获多行字符组
Regex pros,我有一个GoogleTest--gtest_list_测试输出,我需要解析它来获得每个测试套件和案例。输出具有以下格式:Java 捕获多行字符组,java,regex,multiline,Java,Regex,Multiline,Regex pros,我有一个GoogleTest--gtest_list_测试输出,我需要解析它来获得每个测试套件和案例。输出具有以下格式: TestSuite1. TestCase1 TestCase2 TestSuite2. TestCase1 TestCase2 TestCase3 等等。我需要一个java正则表达式模式来捕获每个测试套件及其案例。对于上述输入,我需要将第1组作为 TestSuite1. T
TestSuite1.
TestCase1
TestCase2
TestSuite2.
TestCase1
TestCase2
TestCase3
等等。我需要一个java正则表达式模式来捕获每个测试套件及其案例。对于上述输入,我需要将第1组作为
TestSuite1.
TestCase1
TestCase2
第2组为
TestSuite2.
TestCase1
TestCase2
TestCase3
我似乎不知道该怎么做。目前,我正在使用以下模式:
(.+\\.\\n(?:\\s+.+\\n)+)+
这不管用。谢谢您可以使用此正则表达式捕获分组数据:
[^.\s]+\.(?:\R\h+.+)+
说明:
:匹配任何非点且非空白的字符[^.\s]+
:后跟一个点\。
为测试用例匹配以1+空格开头的一行或多行(?:\R\h++)+
[^.\s]+\.(?:\R\h+.+)+
说明:
:匹配任何非点且非空白的字符[^.\s]+
:后跟一个点\。
为测试用例匹配以1+空格开头的一行或多行(?:\R\h++)+
\n
并省略最后一个量词+
那会匹配的
( # Capturing group
.+ # Any character one more times
\. # Match a dot
\n # Match a newline
(?: # Non capturing group
\s+ # One or more whitespace characters
.+ # Any character one more times
\n? # An optional newline
)+ # Close non capturing group and repeat o 1 or more times
) # Close capturing group
(#捕获组)
.+#任意字符再重复一次
\.#匹配一个点
\n#匹配新行
(?:#非捕获组
\s+#一个或多个空白字符
.+#任意字符再重复一次
\n?#可选换行符
)+#关闭非捕获组并重复1次或更多次
)#近距离捕获组
如果您不想在组1中捕获它,可以使用:
也许您可以选择
\n
并省略最后一个量词+
那会匹配的
( # Capturing group
.+ # Any character one more times
\. # Match a dot
\n # Match a newline
(?: # Non capturing group
\s+ # One or more whitespace characters
.+ # Any character one more times
\n? # An optional newline
)+ # Close non capturing group and repeat o 1 or more times
) # Close capturing group
(#捕获组)
.+#任意字符再重复一次
\.#匹配一个点
\n#匹配新行
(?:#非捕获组
\s+#一个或多个空白字符
.+#任意字符再重复一次
\n?#可选换行符
)+#关闭非捕获组并重复1次或更多次
)#近距离捕获组
如果您不想在组1中捕获它,可以使用:
如果设置多行标志,则可以使用行终止符
$
:
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
-----------
如果设置多行标志,则可以使用行终止符
$
:
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
-----------
很高兴知道它成功了很高兴知道它成功了,