2 cách chính: Character.isDigit() hoặc Regular Expression.
Cách 1: Character.isDigit(char)
public static boolean startsWithDigit(String str) {
if (str == null || str.isEmpty()) return false;
return Character.isDigit(str.charAt(0));
// hoặc: Character.isDigit(str.toCharArray()[0]);
}
Cách 2: Regex matches()
public static boolean startsWithDigitRegex(String str) {
return str != null && str.matches("^\\d.*");
// ^\\d = bắt đầu bằng chữ số, .* = bất kỳ ký tự nào sau đó
}
Ví dụ tương tác
import java.util.Scanner;
public class FirstCharDigitCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Nhập chuỗi: ");
String input = sc.nextLine();
boolean isDigit = Character.isDigit(input.charAt(0));
System.out.println(isDigit ? "✅ Ký tự đầu LÀ số" : "❌ Ký tự đầu KHÔNG phải số");
// Demo regex
System.out.println("Regex: " + input.matches("^\\d.*"));
}
}
Kết quả
Nhập chuỗi: 2sample
✅ Ký tự đầu LÀ số
Regex: true
Nhập chuỗi: hello
❌ Ký tự đầu KHÔNG phải số
Regex: false
Mở rộng: Kiểm tra cả chuỗi có phải số hoàn toàn
// Chỉ chứa digit
str.matches("\\d+") // hoặc str.matches("[0-9]+")
// Số thực (có dấu, thập phân)
str.matches("^[+-]?\\d+(\\.\\d+)?$")
⚠️ Lưu ý Unicode
Character.isDigit()nhận diện chữ số Unicode (ví dụ: ١٢٣ Arabic-Indic, ১২৩ Bengali)- Regex
\\dtrong Java mặc định cũng khớp Unicode digit - Chỉ muốn ASCII 0-9: dùng
[0-9]thay vì\\d