Posix 字符类 p{Lu} Java 正则表达式\
javaobject oriented programmingprogramming更新于 2024/8/1 10:14:00
此类 \p{Lu} 匹配大写字母。
示例 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example1 { public static void main(String args[]) { //从用户读取字符串 System.out.println("输入字符串"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); //正则表达式 String regex = "\p{Lu}"; //编译正则表达式 Pattern pattern = Pattern.compile(regex); //检索匹配器对象 Matcher matcher = pattern.matcher(input); int count = 0; while(matcher.find()) { count++; } System.out.println("大写字符数: "+count); } }
输出
输入字符串 Hello HOW are YOU 大写字符数: 7
示例 2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example2 { public static void main(String args[]) { //匹配小写字母的正则表达式 String regex = "^.*\p{Lu}.*$"; //获取输入数据 Scanner sc = new Scanner(System.in); System.out.println("请输入5个字符串: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //创建一个 Pattern 对象 Pattern p = Pattern.compile(regex); System.out.println("带有拉丁字符的字符串: "); for(int i=0; i<5;i++) { //创建 Matcher 对象 Matcher m = p.matcher(input[i]); if(m.matches()) { System.out.println(m.group()); } } } }
输出
请输入5个字符串: hello how are you This is SAMPLE text 123 465 TEST DATA #$% &# *# 带有拉丁字符的字符串: This is SAMPLE text TEST DATA