与一组字符匹配 Java 正则表达式
Java 正则表达式中的字符类由方括号 “[ ]”定义,字符类匹配一个来自指定或一组可能字符的单个字符。
例如,正则表达式 [abc] 匹配单个字符 a、b 或 c。类似地,“[a-z]”匹配 a 到 z 的一个字符。
示例 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "[a-z]"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); int count =0; while (matcher.find()) { count++; } System.out.println("Number of characters from a to z: "+count); } }
输出
Enter input text: sample data 1234$ Number of characters from a to z: 10
示例 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample1 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter input text: "); String input = sc.nextLine(); String regex = "[^a-z]"; //Creating a pattern object Pattern pattern = Pattern.compile(regex); //Matching the compiled pattern in the String Matcher matcher = pattern.matcher(input); int count =0; while (matcher.find()) { count++; } System.out.println("Number of non-alphabetic characters : "+count); } }
输出
Enter input text: sample data 1234$ Number of non-alphabetic characters : 7
广告