一: 基本用法
\d:等同于字符组 [0-9],表示任意一个数字字符\w:较为常见,等同于字符组[0-9a-zA-Z],表示任意一个world(单词字符)\s:等同于[ \t\n\x0B\f\r],匹配的是一个空格字符(space)当然,它们也有相对应的大写形式,但是表示的意思却是截然相反的。
\D:等同于[^0-9],表示一个任意非数字字符\W:等同于[^0-9a-zA-Z],表示任意一个非单词字符,往往会是一些特殊符号\S:等同于[^\t\n\x0B\f\r],匹配一个任意非空格的字符 public static void main(String[] args){ String msg = "248jhf8ADFV89你好"; String regxt= "\\w"; String newMsg = msg.replaceAll(regxt," "); // System.out.println(newMsg); int numCount=0; //多少个数字 int smallCount =0; //多少小写字母 int bigCount =0; //多少个大写字母 int chinaCount = 0; //多少个汉字 int msgLength = msg.toCharArray().length; for (int i = 0; i< msgLength; i++) { char item = msg.toCharArray()[i]; if(item>='0' && item <='9'){ numCount++; }else if(item>='a' && item <='z'){ smallCount++; }else if(item>='A' && item <='Z'){ bigCount++; }else{ chinaCount++; } } System.out.println(numCount); System.out.println(smallCount); System.out.println(bigCount); System.out.println(chinaCount); }执行结果如下:
你好 6 3 4 2
Process finished with exit code 0
1.1 string split 的正则表达式
public static void main(String[] args){ String msg = "248jhf8ADFV89你好"; String[] msgArray = msg.split("[0-9]"); List<String> list = Arrays.asList(msgArray); // list.stream().forEach( // System.out::println // ); list.stream().forEach(obj -> System.out.println(obj)); }输出结果:
jhf ADFV
你好
public static void main(String [] args){ String str = "cyy,single.abc/https"; String[] results = str.split("[,./]"); for(String s : results){ System.out.print(s+" "); } } 输出结果:cyy single abc https