Java正则表达式字符串解析

3
我尝试使用正则表达式解析字符串以获取其中的参数。例如:
字符串:"TestStringpart1 with second test part2"
结果应该是:String[] {"part1", "part2"}
正则表达式:"TestString(.*?) with second test (.*?)"
我的测试代码如下:
String regexp = "TestString(.*?) with second test (.*?)";
String res = "TestStringpart1 with second test part2";
Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(res); int i = 0; while(matcher.find()) { i++; System.out.println(matcher.group(i)); }
但它只输出了 "part1",有谁能给我指点一下吗?
谢谢!

您可以使用以下网站来检查您的正则表达式是否符合测试用例:https://regex101.com/ - luizfzs
2个回答

2

也许需要修复一些正则表达式

String regexp = "TestString(.*?) with second test (.*)";

修改代码中的println指令..

if (matcher.find())
    for (int i = 1; i <= matcher.groupCount(); ++i)
        System.out.println(matcher.group(i));

1

好的,你只是要求它...在你的原始代码中,find函数不断将匹配器从一个整个正则表达式的匹配项移动到另一个,而在while循环体内,你只提取了一个组。实际上,如果在你的字符串中有多个正则表达式的匹配项,你会发现对于第一次出现,你会得到“part1”,对于第二次出现,你会得到“part2”,而对于任何其他引用,你都会得到一个错误。

while(matcher.find()) {

    System.out.print("Part 1: ");
    System.out.println(matcher.group(1));

    System.out.print("Part 2: ");
    System.out.println(matcher.group(2));

    System.out.print("Entire match: ");
    System.out.println(matcher.group(0));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接