如何使用 Java 正则表达式 (RegEx) 匹配非数字
javaobject oriented programmingprogramming更新于 2024/5/5 10:20:17
您可以使用元字符"\D""匹配非数字字符。
示例 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//从用户读取字符串
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "\D";
//编译正则表达式
Pattern pattern = Pattern.compile(regex);
//检索匹配器对象
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("非数字字符数:"+count);
}
}
输出
输入一个字符串 sample text 2425 36 非数字字符数:13
示例 2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
//接受 5 个字母单词的正则表达式
String regex = "\D{10}";
System.out.println("输入输入值:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean result = input.matches(regex);
if(result) {
System.out.println("输入匹配");
}
else {
System.out.println("输入错误");
}
}
}
输出 1
输入值: sample abc 输入匹配
输出 2
输入值: sample1234 输入错误
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

