Bạn có thể khớp chữ số trong chuỗi cho trước bằng metaký tự "\\d" hoặc bằng biểu thức sau:
[0-9]
Ví dụ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// Đọc chuỗi từ người dùng
System.out.println("Nhập một chuỗi");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\\d";
// Biên dịch biểu thức chính quy
Pattern pattern = Pattern.compile(regex);
// Lấy đối tượng matcher
Matcher matcher = pattern.matcher(input);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("Số chữ số: " + count);
}
}
Kết quả
Nhập một chuỗi sample text 1234 6657 Số chữ số: 8
Ví dụ 2
import java.util.Scanner;
public class RegexExample {
public static void main(String args[]) {
// Biểu thức chính quy chấp nhận 10 chữ số
String regex = "\\d{10}";
System.out.println("Nhập giá trị đầu vào: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean result = input.matches(regex);
if (result) {
System.out.println("Số 10 chữ số");
} else {
System.out.println("đầu vào sai");
}
}
}
Kết quả 1
Nhập giá trị đầu vào: 9848022558 Số 10 chữ số
Kết quả 2
Nhập giá trị đầu vào: 5337 đầu vào sai