你能看一下下面结果中的模式(java)吗?我预计结果应该给我 3 个组值,但相反它给了我 2 个值,只是我认为我错过了一些东西。
package com.mycompany.testapp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author bo17a
*/
public class NewClass {
public static void main(String[] args){
Pattern mPattern = Pattern.compile("^love (.*?) way you (.*?)$");
Matcher matcher = mPattern.matcher("love the way you lie");
if(matcher.find()){
String[] match_groups = new String[matcher.groupCount()];
System.out.println(String.format("groupCount: %d", matcher.groupCount()));
for(int j = 0;j<matcher.groupCount();j++){
System.out.println(String.format("j %d",j));
match_groups[j] = matcher.group(j);
System.out.println(match_groups[j]);
}
}
}
}
我得到的结果是:
2
love the way you lie
the
但我的预期结果应该是:
3
love the way you lie
the
lie
更新
我尝试按照回复中的建议添加一组号码:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.testapp;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author lee
*/
public class NewClass {
public static void main(String[] args){
Pattern mPattern = Pattern.compile("^love (.*?) way you (.*?)$");
Matcher matcher = mPattern.matcher("love the way you lie");
if(matcher.find()){
String[] match_groups = new String[matcher.groupCount()];
System.out.println(String.format("groupCount: %d", matcher.groupCount()));
for(int j = 0;j<=matcher.groupCount();j++){
System.out.println(String.format("j %d",j));
match_groups[j] = matcher.group(j);
System.out.println(match_groups[j]);
}
}
}
}
我已经在 Windows 10 JDK 8 Mac OS JDK 8 上尝试过。那么,这可能是 Java 中的一个错误,因为你和我对相同的代码有不同的结果?
狐的传说
九州编程
相关分类