Java中的正则表达式“d”结构
子表达式/元字符“\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"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } }
输出
Number of matches: 2
示例 2
以下是一个 Java 程序,该程序从用户处读取一个 10 位数。
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("Enter your phone number (10 digits): "); String input = sc.nextLine(); //Creating a Pattern object Pattern p = Pattern.compile(regex); //Creating a Matcher object Matcher m = p.matcher(input); if(m.find()) { System.out.println("OK"); } else { System.out.println("Wrong input"); } } }
输出 1
Enter your phone number (10 digits): 9848022338 OK
输出 2
Enter your phone number (10 digits): 545 Wrong input
广告