Java 中的正则表达式"d"构造
javaobject oriented programmingprogramming更新于 2024/5/5 1:16:17
子表达式/元字符"\d"与数字匹配。
示例 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "\d 24";
String input = "This is sample text 12 24 56 89 24";
模式 p = Pattern.compile(regex);
匹配器 m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("匹配数:"+count);
}
}
输出
匹配数:2
示例 2
以下是一个从用户那里读取 10 位数字的 Java 程序。
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
String regex = "\d{10}";
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的电话号码(10位数字):");
String input = sc.nextLine();
//创建一个 Pattern 对象
Pattern p = Pattern.compile(regex);
//创建一个 Matcher 对象
Matcher m = p.matcher(input);
if(m.find()) {
System.out.println("OK");
} else {
System.out.println("输入错误");
}
}
}
输出 1
输入您的电话号码(10 位数字): 9848022338 OK
输出 2
输入您的电话号码(10 位数字): 545 输入错误
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

