2 回答

TA貢獻1804條經驗 獲得超3個贊
我的猜測是,您還希望以團隊形式捕捉完整比賽,
^(love (.*?) way you (.*?))$
或者直接在你的計數器上加 1:
測試1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
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() + 1];
System.out.println(String.format("groupCount: %d", matcher.groupCount() + 1));
for(int j = 0;j<matcher.groupCount() + 1;j++){
System.out.println(String.format("j %d",j));
match_groups[j] = matcher.group(j);
System.out.println(match_groups[j]);
}
}
}
}
輸出
groupCount: 3
j 0
love the way you lie
j 1
the
j 2
lie
測試2
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "^(love (.*?) way you (.*?))$";
final String string = "love the way you lie";
final Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
輸出
Full match: love the way you lie
Group 1: love the way you lie
Group 2: the
Group 3: lie
正則表達式電路
jex.im可視化正則表達式:

TA貢獻1785條經驗 獲得超4個贊
顯然,matcher.groupCount()
在您的情況下返回 2,因此您只需構造兩個字符串的數組并將數字小于 2 的組復制到其中,即組 0(整個字符串)和組 1(“the”)。如果您matcher.groupCount()
在整個代碼中添加 1,它將按預期工作。
添加回答
舉報