捕获多行字符组
Capturing multiline character groups
Regex 专家,我有一个 GoogleTest --gtest_list_tests 输出,我需要对其进行解析以获取每个测试套件和案例。输出具有以下格式:
TestSuite1.
TestCase1
TestCase2
TestSuite2.
TestCase1
TestCase2
TestCase3
等等。我需要一个 java 正则表达式模式来捕获每个测试套件及其用例。对于上述输入,我需要将第 1 组设置为
TestSuite1.
TestCase1
TestCase2
第 2 组为
TestSuite2.
TestCase1
TestCase2
TestCase3
我似乎不知道如何让它发挥作用。现在我正在使用这种模式:
(.+\.\n(?:\s+.+\n)+)+
这是行不通的。谢谢
您可以使用此正则表达式来捕获分组数据:
[^.\s]+\.(?:\R\h+.+)+
解释:
[^.\s]+
: 匹配任何不是点和空格的字符
\.
: 后跟一个点
(?:\R\h+.+)+
为测试用例匹配以 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
如果你不想在组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
-----------
Regex 专家,我有一个 GoogleTest --gtest_list_tests 输出,我需要对其进行解析以获取每个测试套件和案例。输出具有以下格式:
TestSuite1.
TestCase1
TestCase2
TestSuite2.
TestCase1
TestCase2
TestCase3
等等。我需要一个 java 正则表达式模式来捕获每个测试套件及其用例。对于上述输入,我需要将第 1 组设置为
TestSuite1.
TestCase1
TestCase2
第 2 组为
TestSuite2.
TestCase1
TestCase2
TestCase3
我似乎不知道如何让它发挥作用。现在我正在使用这种模式:
(.+\.\n(?:\s+.+\n)+)+
这是行不通的。谢谢
您可以使用此正则表达式来捕获分组数据:
[^.\s]+\.(?:\R\h+.+)+
解释:
[^.\s]+
: 匹配任何不是点和空格的字符\.
: 后跟一个点(?:\R\h+.+)+
为测试用例匹配以 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
如果你不想在组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
-----------