正則表示式「G」元字元在 Java 中


子表示式/元字元“\G”匹配上次匹配結束的位置。

示例

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
   public static void main( String args[] ) {
      String regex = "\G[0-9]";
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a string: ");
      String input = sc.nextLine();
      Pattern p = Pattern.compile(regex);
      Matcher m = p.matcher(input);
      int count = 0;
      String digits = "";
      System.out.println("Digits in the previous match:");
      while(m.find()) {
         System.out.print(m.group());
         count ++;
      }
      System.out.println();
      System.out.println("Number of matches: "+count);
   }
}

輸出

Enter a string:
555 sample text
Digits in the previous match:
555
Number of matches: 3

更新於:19-Nov-2019

756次瀏覽

開啟您的職業生涯

完成該課程,獲取認證

開始學習
廣告
© . All rights reserved.