如何使用 Java 正則表示式捕獲同一行中的多個匹配項


示例

import java.util.regex.*;
class PatternMatcher {
   public static void main(String args[]) {
      int count = 0;
      // String to be scanned to find the pattern.
      String content = "aaa bb aaa";
      String string = "aaa";

      // Create a Pattern object
      Pattern p = Pattern.compile(string);

      // get a matcher object
      Matcher m = p.matcher(content);

      while(m.find()) {
         count++;
         System.out.println("Match no:"+count);
         System.out.println("Found at: "+ m.start()+ " - " + m.end());
      }
   }
}

輸出

Match no:1
Found at: 0 - 3
Match no:2
Found at: 7 - 10

備註

  • start() – 此方法用於獲取使用 find() 方法找到的匹配項的起始索引。

  • end() – 此方法用於獲取使用 find() 方法找到的匹配項的結束索引。它返回最後一個匹配字元後面的字元索引。

更新時間:2020 年 6 月 20 日

超過 3 千次瀏覽

開啟動你的 職業生涯

完成課程獲得認證

開始
廣告