javaRegex:group()詳解

來源:互聯網
上載者:User


import  java.util. * ;
import  java.util.regex.Matcher;
import  java.util.regex.Pattern;
 
public   class  Fenzhu
  ... {
      public   static   void  main(String[] args)
      ... {
             Pattern p  =  Pattern.compile( " (/d{3,5})([a-z]{2}) " );
             String s  =   " 123aa-34345bb-234cc-00 " ;
             Matcher m  =  p.matcher(s);
              while (m.find()) 
              ... {
                  System.out.println( " m.group(): " + m.group());  // 列印所有
                   
                  System.out.println( " m.group(1): " + m.group( 1 ));  // 列印數位
                   
                  System.out.println( " m.group(2): " + m.group( 2 ));  // 列印字母的
                  System.out.println();
                  
           }     
           System.out.println( " 捕獲個數:groupCount()= " + m.groupCount());
      }
 }
 

 

輸出結果為

 

 

附:協助文檔的說明 group

public String group(int group)
返回在以前匹配操作期間由給定組捕獲的輸入子序列。

對於匹配器 m 、輸入序列 s 和組索引 g ,運算式 m. group( g ) 和 s. substring( m. start( g ),  m. end( g )) 是等效的。

擷取的群組是從 1 開始從左至右的索引。組零表示整個模式,因此運算式 m.group(0) 等效於 m.group() 。

如果該匹配成功了,但指定組未能匹配輸入序列的任何部分,則返回 null 。注意,某些組(例如,(a*) )匹配Null 字元串。當這些的組成功匹配輸入中的Null 字元串時,此方法將返回Null 字元串。

  指定者: 介面 MatchResult 中的 group 參數: group - 此匹配器模式中擷取的群組的索引。 返回: 在以前的匹配期間組所捕獲的子序列(可能為空白);如果組未能匹配輸入的部分,則返回 null 。 拋出: IllegalStateException - 如果沒有嘗試任何匹配,或者以前的匹配操作失敗。 IndexOutOfBoundsException - 如果在給定索引的模式中不存在擷取的群組。 groupCount

public int groupCount()
返回此匹配器模式中的擷取的群組數。

根據慣例,零組表示整個模式。它不包括在此計數中。

任何小於等於此方法傳回值的非負整數保證是此匹配器的有效組索引。

  指定者: 介面 MatchResult 中的 groupCount 返回: 此匹配器模式中的擷取的群組數。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.