使用 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