使用 Java 正則表示式匹配不可列印字元


有 7 個常用的不可列印字元,且每個字元都有其自己的十六進位制表示。

名稱字元十六進位制表示
響鈴\a0x07
轉義\e0x1B
換頁符\f0x0C
換行符\n0x0A
回車符\r0X0D
水平製表符\t0X09
垂直製表符\v0X0B

示例 1

 線上演示

以下 Java 程式接受輸入文字並計算其中的製表符數量 −

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 = "\t";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number of tab spaces in the given iput text: "+count);
   }
}

輸出

sample text with tab spaces
Number of tab spaces in the given input text: 3

示例 2

 線上演示

您還可以使用不可列印字元的相應十六進位制表示來進行匹配。

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 = "\x09";
      //Creating a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Matching the compiled pattern in the String
      Matcher matcher = pattern.matcher(input);
      int count =0;
      while (matcher.find()) {
         count++;
      }
      System.out.println("Number of tab spaces in the given iput text: "+count);
   }
}

輸出

Enter input text:
sample data with tab spaces
Number of tab spaces in the given input text: 4

更新於: 2020 年 1 月 13 日

898 次瀏覽

開啟您的 事業

完成課程,獲得認證

開始
廣告
© . All rights reserved.