Java 中的正则表达式"D"元字符
javaobject oriented programmingprogramming
子表达式/元字符"\D"与非数字匹配。
示例 1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\D"; 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); } }
输出
匹配数:24
示例2
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "\D"; Scanner sc = new Scanner(System.in); System.out.println("请输入5个字符串: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //创建一个 Pattern 对象 Pattern p = Pattern.compile(regex); System.out.println("每个字符串中的非数字字符数:"); for(int i=0; i<5;i++) { //创建一个 Matcher 对象 Matcher m = p.matcher(input[i]); int count = 0; while(m.find()) { count++; } System.out.println("字符串 "+i+": "+count); } } }
输出
请输入5个字符串: sample 1 12 35 36 63 test 243 663 hello hello how are you * 每个字符串中非数字字符的数量: 字符串0: 7 字符串1: 3 字符串2: 6 字符串3: 5 字符串4: 19