Posix 字符类 p{XDigit} Java 正则表达式。
javaobject oriented programmingprogramming更新于 2025/2/6 7:40:17
此类匹配十六进制字符,即 [0-9a-fA-F]。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SpaceCharacters {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("输入字符串");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
//正则表达式
String regex = "[\p{XDigit}]";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("十六进制字符数: "+count);
}
}
输出
输入字符串 Bb12\tc! 十六进制字符数: 5
示例 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{XDigit}.*$";
//获取输入数据
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 123 xyz @## DEF01 包含十六进制字符的字符串: sample 123 DEF01
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

