Java正则表达式程序,用于验证字符串是否包含至少一个字母数字字符。
以下正则表达式匹配包含至少一个字母数字字符的字符串-
"^.*[a-zA-Z0-9]+.*$";
哪里,
^。*匹配以零个或多个(任何)字符开头的字符串。
[a-zA-Z0-9]+匹配至少一个字母数字字符。
。*$匹配以零个或多个(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