如何使用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[]) { //从用户读取字符串 System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "^[a-zA-Z0-9]*$"; //编译正则表达式 Pattern pattern = Pattern.compile(regex); //检索匹配器对象 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[]) { //从用户读取字符串 System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "[0-9&&[^35]]"; //编译正则表达式 Pattern pattern = Pattern.compile(regex); //检索匹配器对象 Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("Occurrences :"+count); } }
输出结果
Enter a String 111223333555689 Occurrences :8