标签:
1 import java.util.regex.Matcher; 2 import java.util.regex.Pattern; 3 4 public class RegexDemo { 5 6 public static void main(String[] args) { 7 method_5(); 8 } 9 10 /* 11 * 需求:定义一个功能对QQ号进行校验。 要求:长度5~15. 只能是数字, 0不能开头 12 */ 13 public static void method_1() { 14 String qq = "101885"; 15 String regex = "[1-9]\\d{4,14}"; 16 System.out.println(qq + ":" + qq.matches(regex)); 17 } 18 19 /* 20 * 需求:手机号码验证 21 */ 22 public static void method_2() { 23 String tel = "18190029004"; 24 String regex = "1[358]\\d{9}"; 25 System.out.println(tel + ":" + tel.matches(regex)); 26 } 27 28 /* 29 * 需求:叠词切割 30 */ 31 public static void method_3() { 32 String str = "akjdhkahjjauuuuqjhadwww;k"; 33 String regex = "(.)\\1+"; 34 String[] arr = str.split(regex); 35 for (String s : arr) { 36 System.out.println(s); 37 } 38 } 39 40 /* 41 * 需求:替换 1.手机号部分替换 2.叠词替换 42 */ 43 public static void method_4() { 44 String tel = "13840056789"; 45 String regex = "(\\d{3})(\\d{4})(\\d{4})"; 46 System.out.println(tel.replaceAll(regex, "$1****$3")); 47 48 String str = "akjdhkahjjauuuuqjhadwww;k"; 49 String reg = "(.)\\1+"; 50 System.out.println(str.replaceAll(reg, "*")); 51 } 52 53 /* 54 * 需求:获取 三个字母的单词 55 */ 56 public static void method_5() { 57 String str = "ajkdh iqw iqiw qii,wip aido q qw"; 58 String regex = "\\b[a-z]{3}\\b"; 59 Pattern p = Pattern.compile(regex); 60 Matcher m = p.matcher(str); 61 while (m.find()) { 62 System.out.println(m.group()); 63 System.out.println(m.start() + " " + m.end()); 64 } 65 } 66 }
标签:
原文地址:http://www.cnblogs.com/linson0116/p/4191607.html