Java Stringparsing with Regexp
我尝试用regexp解析一个字符串,以从中获取参数。例如:
1 2 3
| String:"TestStringpart1 with second test part2"
Result should be : String[] {"part1", "part2"}
Regexp :"TestString(.*?) with second test (.*?)" |
我的测试代码是:
1 2 3 4 5 6 7 8 9 10
| 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 ));
} |
号
但它只输出"第1部分"有人能给我提示吗?
谢谢
- 您可以使用以下站点根据测试用例检查您的regex:regex101.com
可能是一些修复regexp
1
| String regexp ="TestString(.*?) with second test (.*)"; |
并更改println代码。
1 2 3
| if (matcher. find())
for (int i = 1; i <= matcher. groupCount(); ++i )
System. out. println(matcher. group(i )); |
号
嗯,你只要求…在您的原始代码中,find不断地将matcher从整个正则表达式的一个匹配项转移到下一个匹配项,而在while的主体中,您只能拉出一个组。实际上,如果您的字符串中有多个regexp匹配项,您会发现对于第一个匹配项,您会得到"part1",对于第二个匹配项,您会得到"part2",对于任何其他引用,您都会得到一个错误。
1 2 3 4 5 6 7 8 9 10 11
| 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));
} |