Matcher的group()/group(int group)/groupCount()用法介绍

直接上代码:

package com.dajiangtai.djt_spider.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MatcherTest {
public static void main(String[] args)
throws Exception {

Pattern p = Pattern.compile("(ca)(t)");
Matcher m = p.matcher("one cat,two cats in the yard");
StringBuffer sb = new StringBuffer();
boolean result = m.find();
System.out.println("该次查找获得匹配组的数量为:"+m.groupCount()); //2
for(int i=0;i<=m.groupCount();i++){
System.out.println("第"+i+"组的子串内容为:"+m.group(i));
}
}
}

输出:

该次查找获得匹配组的数量为:2
第0组的子串内容为:cat
第1组的子串内容为:ca
第2组的子串内容为:t

可以这样理解:m.groupCount()表示()的个数。

m.group(0)表示要匹配满足正则表达式中所有括号里的字符串的第一个值,因此为cat

m.group(1)表示匹配正则表达式中的第一个括号里的内容即可,因此为ca,注意,也是第一次的值

m.group(2)表示匹配正则表达式中的第二个括号里的内容即可,因此为t,注意,也是第一次的值

原文地址:https://www.cnblogs.com/lchzls/p/6277929.html