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,它将按预期工作。
添加回答
举报