参考网上相关blog,对Java字符串的匹配问题进行了简单的比较和总结,主要对String类的matches方法与Matcher类的matches方法进行了比较。
对Matcher类的matches()、find()和lookingAt()三个容易混淆的方向进行了比较说明。
在这里对参考的相关blog的原创者一并谢过,谢谢!
话不多说,呈上代码:
1 /** 2 * 判断一个字符串是否包含数字;是否只含数字;输出匹配到的字串 3 * @author JiaJoa 4 * 5 */ 6 public class StringIsDigit { 7 8 public static void main(String[] args) { 9 String str = "2017花花0512麻麻"; 10 System.out.println(stringContainDigit(str)); //true 11 System.out.println(stringIsAllDigit(str)); //false 12 System.out.println(stringIsAllDigit1(str)); //false 13 System.out.println(stringIsAllDigit2(str)); //false 14 System.out.println(stringIsAllDigit3(str)); //false 15 System.out.println(getMatchGroup(str)); //2017 0512 16 } 17 18 19 //使用String matches方法结合正则表达式一个字符串是否包含数字 20 public static boolean stringContainDigit(String str){ 21 String regex = ".*\\d+.*"; //判断是否包含字母,改为 .*[a-zA-Z]+.* 是否包含汉字改为 .*[\u4e00-\u9fa5].* 22 return str.matches(regex); 23 } 24 25 26 //使用Character类的isDigit方法判断一个字符串是否只包含数字 27 public static boolean stringIsAllDigit(String str){ 28 for(int i=0;i<str.length();i++){ 29 if(!Character.isDigit(str.charAt(i))) 30 return false; 31 } 32 return true; 33 } 34 35 //使用0-9对应的ASCII码范围判断一个字符串是否只包含数字 36 public static boolean stringIsAllDigit1(String str){ 37 for(int i=0;i<str.length();i++){ 38 int charn = str.charAt(i); 39 if(charn<48||charn>58){ 40 return false; 41 } 42 } 43 return true; 44 } 45 46 47 //使用String类的matches方法判断一个字符串是否只包含数字 48 public static boolean stringIsAllDigit2(String str){ 49 String regex = "\\d+"; 50 return str.matches(regex); 51 } 52 53 //使用Matcher类的matches方法判断一个字符串是否只包含数字 54 public static boolean stringIsAllDigit3(String str){ 55 String regex = "[0-9]+"; 56 Pattern pattern = Pattern.compile(regex); 57 Matcher matcher = pattern.matcher((CharSequence)str); 58 return matcher.matches(); //matcher.matches()是全匹配,而matcher.find()是找到符合条件的匹配就返回true 59 } 60 61 //使用Matcher类的group方法输出匹配到的结果串 62 public static String getMatchGroup(String str){ 63 String regex = "[0-9]+"; 64 Pattern pattern = Pattern.compile(regex); 65 Matcher matcher = pattern.matcher((CharSequence)str); 66 StringBuilder sb = new StringBuilder(); 67 68 /* 69 * matcher.matches()是全匹配,只有整个匹配串完全匹配才返回true,如果前部分匹配成功,会继续匹配剩下的位置。 70 * matcher.find()是部分匹配,找到一个匹配字串后,将移动下次匹配直到匹配串尾部 71 * matcher.lookingAt()是部分匹配,从第一个字符进行匹配,匹配成功了不再继续匹配,匹配失败了,也不继续匹配 72 */ 73 while(matcher.find()){ 74 sb.append(matcher.group()+" "); 75 } 76 return sb.toString(); 77 } 78 79 }
转载于:https://www.cnblogs.com/JiaJoa/p/6847230.html
相关资源:JAVA上百实例源码以及开源项目