Java 正則表示式程式驗證字串中是否至少包含一個字母數字字元。
以下正則表示式匹配包含至少一個字母數字字元的字串 -
"^.*[a-zA-Z0-9]+.*$";
其中,
^.* 匹配從零個或更多(任意)字元開始的字串。
[a-zA-Z0-9]+ 匹配至少一個字母數字字元。
.*$ 匹配以零個或更多(任意)字元結尾的字串。
示例 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
廣告