Phần biểu thức/metaký tự “\G” khớp với điểm nơi khớp trước đó kết thúc.
Ví dụ
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("Nhập một chuỗi: ");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
String digits = "";
System.out.println("Chữ số trong khớp trước:");
while (m.find()) {
System.out.print(m.group());
count++;
}
System.out.println();
System.out.println("Số lần khớp: " + count);
}
}
Kết quả
Nhập một chuỗi: 555 sample text Chữ số trong khớp trước: 555 Số lần khớp: 3