以下正则表达式匹配包含至少一个字母数字字符的字符串-
"^.*[a-zA-Z0-9]+.*$";
哪里,
^。*匹配以零个或多个(任何)字符开头的字符串。
[a-zA-Z0-9] +匹配至少一个字母数字字符。
。* $匹配以零个或多个(ant)字符结尾的字符串。
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"); } } }
Enter a string ###test123$$$ Given string is valid
Enter a string ####$$$$ Given string is not valid
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"); } } }
Enter a string ###test123$$$ Valid match
Enter a string ####$$$$ In valid match