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

javaobject oriented programmingprogramming更新于 2025/7/13 10:52:17

此类匹配所有制表符或空格。

示例 

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PrintableCharacters {
   public static void main(String args[]) {
      //从用户读取字符串
      System.out.println("输入字符串");
      Scanner sc = new Scanner(System.in);
      String input = sc.nextLine();
      //正则表达式
      String regex = "[\p{Blank}]";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      while(matcher.find()) {
         count++;
      }
      System.out.println("空白字符数: "+count);
   }
}

输出

输入字符串
space tab test
空白字符数: 2

示例 

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      //匹配小写字母的正则表达式
      String regex = "^.*\p{Blank}.*$";
      //获取输入数据
      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个字符串:
sample data
hello
welcome to tutorialspoint
12345
ab bc cd da
含有空白字符的字符串:
sample data
welcome to tutorialspoint
ab bc cd da

相关文章


有用资源