如何使用 Java 正则表达式 (RegEx) 匹配数字
javaobject oriented programmingprogramming更新于 2024/5/5 9:48:17
您可以使用元字符"\d"或使用以下表达式匹配给定字符串中的数字:
[0-9]
示例 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 1234 6657 数字数量:8
示例 2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
//接受 10 位数字的正则表达式
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("10 位数字");
} else {
System.out.println("输入错误");
}
}
}
输出 1
输入值: 9848022558 10 位数字
输出 2
输入值: 5337 输入错误
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

