計算 Java 正則表示式中的組數


可以透過將多個字元組合成組對其進行捕獲,將多個字元視為一個單獨的單元。只需將這些字元放在一對括號中即可。

可以使用 Matcher 類的 groupCount() 方法計算當前匹配中的組數。此方法計算當前匹配中捕獲的組數並返回該值。

示例

 Live Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
   public static void main(String[] args) {
      String str1 = "<p>This <b>is</b> an <b>example</b> HTML <b>script</b> where <b>ever</b> alternative <b>word</b> is <b>bold</b></p>.";
      //Regular expression to match contents of the bold tags
      String regex = "(t(\S+)t)(\s)";
      String str = "the words tit tat tweet tostff tact that tilt text. start and end with the letter       t    ";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(str);
      while (matcher.find()) {
         System.out.println(matcher.group(0));
      }
      System.out.println("Total capturing groups: "+matcher.groupCount());
   }
}

輸出

tit
tat
tweet
tact
that
tilt
text
tart
Total capturing groups: 3

更新於: 13-Jan-2020

996 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.