標籤:
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 }
Regex1