다음 정규식은 하나 이상의 영숫자를 포함하는 문자열과 일치합니다 -
"^.*[a-zA-Z0-9]+.*$";
어디,
-
^.* 0개 이상의(임의) 문자로 시작하는 문자열과 일치합니다.
-
[a-zA-Z0-9]+ 하나 이상의 영숫자 문자와 일치합니다.
-
. *$ 0개 이상의(ant) 문자로 끝나는 문자열과 일치합니다.
예시 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");
}
}
} 출력 1
Enter a string ###test123$$$ Given string is valid
출력 2
Enter a string ####$$$$ Given string is not valid
예시 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");
}
}
} 출력 1
Enter a string ###test123$$$ Valid match
출력 2
Enter a string ####$$$$ In valid match