2 回答

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超3個(gè)贊
我的猜測(cè)是,您還希望以團(tuán)隊(duì)形式捕捉完整比賽,
^(love (.*?) way you (.*?))$
或者直接在你的計(jì)數(shù)器上加 1:
測(cè)試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
測(cè)試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
正則表達(dá)式電路
jex.im可視化正則表達(dá)式:

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