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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM