Posix 字符类 p{ASCII} Java 正则表达式。

javaobject oriented programmingprogramming更新于 2025/2/2 3:24:17

此类匹配 ASCII 字符,即 \x00-\x7F。

示例

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("输入字符串");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //正则表达式
      String regex = "^[\p{ASCII}]";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("给定字符串中非 ASCII 字符的数量:"+count);
   }
}

输出

输入字符串
why do we fall
给定字符串中非 ASCII 字符的数量:1

相关文章


有用资源