关于group()、group(int group)、groupCount()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yushenzaishi/article/details/76273030

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,注意,也是第一次的值


猜你喜欢

转载自blog.csdn.net/yushenzaishi/article/details/76273030
今日推荐