Java正则表达式中的字符类使用方括号“ []”定义,字符类与指定字符或一组可能的字符中的单个字符匹配。
例如,正则表达式[abc]匹配单个字符a或b或c。同样,“ [az]”将字符从a匹配到z。
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]"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //匹配字符串中的已编译模式 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
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]"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //匹配字符串中的已编译模式 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