Java学习之正则表达式
1 public static void main(String[] args) { 2 /* 3 * 正则表达式对字符串的常见操作 4 * 5 * 1、匹配 6 * String类中matches 7 * 8 * 2、切割 9 * String类中split 10 * 3、替换 11 * String类中replaceAll 12 * 4、获取 13 * 将正则规则封装成对象 14 * Pattern p = Pattern.compile("a*b"); 15 * 通过正则对象的matcher方法字符串相关联,获取匹配器读写 16 * Matcher Matcher m = p.matcher("aaaab"); 17 * 通过Matcher匹配器对象的方法对字符串进行操作 18 * boolean b = m.matches(); 19 * 20 */ 21 22 getString(); 23 } 24 25 /** 26 * 27 */ 28 private static void getString() { 29 /* 30 * 获取三个字符的单词 31 */ 32 String str = "jin tian tian qi zhen de bu cuo"; 33 34 String regex = "\\b[a-z]{3}\\b"; 35 36 Pattern p = Pattern.compile(regex); 37 38 Matcher m = p.matcher(str); 39 //获取之前先查找 40 while (m.find()) { 41 System.out.println(m.group());// 获取匹配的子序列 42 } 43 44 } 45 46 /** 47 * 48 */ 49 private static void stringReplace() { 50 51 String str = "zhangttttlimmmzhaonnnnnxiao"; 52 String regex = "(.)\\1+"; 53 /* 54 * 剔除重复 55 * 56 * $1: $:获取前一个元素的 1:第一组 57 */ 58 str = str.replaceAll(regex, "$1"); 59 str = "15823461111"; 60 str = str.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"); 61 System.out.println(str); 62 } 63 64 /** 65 * 66 */ 67 private static void stringSplit() { 68 String str="zhang li zhao xiao"; 69 /* 70 * 多空格切割 71 */ 72 String regex=" +"; 73 74 String str = "zhangttttlimmmzhaonnnnnxiao"; 75 /* 76 * 重复字符切割 77 * 78 * 组:((A)(B(C))),括号代表组,组的标号是从1开始的 79 * 80 * (.)\\1+ 解释:任意字符为第一组,第二位置\\1表示和第一组(1代表是第一组)字符一样,+代表组的重复1次或多次 81 */ 82 String regex = "(.)\\1+"; 83 84 String[] names = str.split(regex); 85 for (String name : names) { 86 System.out.println(name); 87 } 88 89 } 90 91 /** 92 * 93 */ 94 private static void stringMatches() { 95 // 匹配手机号码是否正确 96 97 String telString = "15800001111"; 98 String regex = "1[358][0-9] {9}";// String regex="1[358]\\d {9}"; 99 boolean b = telString.matches(regex); 100 101 System.out.println(b); 102 }