使用 Java 正則表示式匹配不可列印字元
有 7 個常用的不可列印字元,且每個字元都有其自己的十六進位制表示。
| 名稱 | 字元 | 十六進位制表示 |
|---|---|---|
| 響鈴 | \a | 0x07 |
| 轉義 | \e | 0x1B |
| 換頁符 | \f | 0x0C |
| 換行符 | \n | 0x0A |
| 回車符 | \r | 0X0D |
| 水平製表符 | \t | 0X09 |
| 垂直製表符 | \v | 0X0B |
示例 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
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP