如何使用 Java 正則表示式匹配一系列字元
若要匹配一系列字元,即要匹配序列中兩個指定字元之間的所有字元,可以用字元類
[a-z]
表示式“[a-zA-Z]”接受任何英文字母。
表示式“[0-9&&[^35]]”接受 3 和 5 以外的數字。
示例 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(); String regex = "^[a-zA-Z0-9]*$"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); if(matcher.matches()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
輸出 1
Enter a String Hello Match occurred
輸出 2
Enter a String sample# Match not occurred
示例 2
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(); String regex = "[0-9&&[^35]]"; //Compiling the regular expression Pattern pattern = Pattern.compile(regex); //Retrieving the matcher object Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Occurrences :"+count); } }
輸出
Enter a String 111223333555689 Occurrences :8
廣告