Biểu thức chính quy theo sau khớp với một chuỗi có chứa ít nhất một ký tự chữ và số -
"^.*[a-zA-Z0-9]+.*$";
Ở đâu,
-
^. * Khớp chuỗi bắt đầu bằng không hoặc nhiều hơn (bất kỳ) ký tự.
-
[a-zA-Z0-9] + Đối sánh ít nhất một ký tự chữ và số.
-
. * $ Đối sánh chuỗi kết thúc bằng không hoặc nhiều ký tự (ant).
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[]) {
//Reading String from user
System.out.println("Enter a string");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression
String regex = "^.*[a-zA-Z0-9]+.*$";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
if(matcher.matches()) {
System.out.println("Given string is valid");
} else {
System.out.println("Given string is not valid");
}
}
} Đầu ra 1
Enter a string ###test123$$$ Given string is valid
Đầu ra 2
Enter a string ####$$$$ Given string is not valid
Ví dụ 2
import java.util.Scanner;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a string");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//Regular expression
String regex = "^.*[a-zA-Z0-9]+.*$";
boolean result = input.matches(regex);
if(result) {
System.out.println("Valid match");
}else {
System.out.println("In valid match");
}
}
} Đầu ra 1
Enter a string ###test123$$$ Valid match
Đầu ra 2
Enter a string ####$$$$ In valid match