第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > Matcher的group()/group(int group)/groupCount()用法介绍

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

时间:2018-08-05 11:12:45

相关推荐

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

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。