Phần biểu thức/metaký tự “re*” khớp 0 hoặc nhiều lần xuất hiện của biểu thức đi trước.
Ví dụ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "aabc*";
String input = "aabcabcaabcabbcaabcbcaabc";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("Số lần khớp: " + count);
}
}
Kết quả
Số lần khớp: 4
Ví dụ 2
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchAllCharacters {
public static void main(String args[]) {
String regex = "(.*)?(\\d+)";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi đầu vào: ");
String input[] = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
// Tạo đối tượng Pattern
Pattern p = Pattern.compile(regex);
System.out.println("Các chuỗi chứa chữ số: ");
for (int i = 0; i < 5; i++) {
// Tạo đối tượng Matcher
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
Kết quả
test data hello how are you 335 welcome to Tutorialspoint Các chuỗi chứa chữ số: sample text 1 hello how are you 335