如何使用 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 千次浏览

开启动你的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.