English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
子表达式/元字符“ \ d ”与数字匹配。
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"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("匹配数: ");+count); } }
输出结果
匹配数: 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("确定"); } else { System.out.println("错误的输入"); } } }
请输入您的电话号码(10 数字: 9848022338 确定
请输入您的电话号码(10 数字: 545 错误的输入