標籤:blog image oid cut 替換 str1 code void []
1 import java.util.Arrays; 2 3 /* 4 Regex的作用: 5 6 1 匹配 7 8 2 切割 9 10 3 替換11 12 * */13 public class Demo1 {14 public static void main(String[] args) {15 isPhone("0314-16610306");16 cutStr1("火 影 忍 者");17 cutStr2("大家家明天天玩的的的的的開心");18 replaceSame("大家家明天天玩的的的的的開心");19 }20 21 //匹配固話: 區號-主機號 區號:首位為0,長度為3-4位 主機號:首位不能為0,長度7-8位22 public static void isPhone(String phone){23 System.out.println(phone.matches("0\\d{2,3}-[1-9]\\d{6,7}")?"合法固話 ":"非法固話");24 }25 26 //切割 通過split27 //需求:按照空格切割字串 = 火 影 忍 者28 public static void cutStr1(String str){29 String[] splits = str.split(" +");30 System.out.println("數組元素:" + Arrays.toString(splits));31 }32 //需求:按照疊詞分割字串=大家家明天天玩的的的的的開心33 public static void cutStr2(String str){34 String[] splits = str.split("(.)\\1+");35 System.out.println("數組元素:" + Arrays.toString(splits));36 }37 38 //替換39 //字串去重:大家家明天天玩的的的的的開心40 public static void replaceSame(String str){ 41 //把後幾號替換成****42 String s = "大家家明13211525558天天玩18356457889的的的的的開心";43 System.out.println("被替換後的內容" + s.replaceAll("1[3478]\\d{9}+", "****"));44 45 //去重並替換46 System.out.println(str.replaceAll("(.)\\1+", "$1"));47 //(.)任意字字元成組,\\1捕獲1次;疊詞,$1得到1組, 取前面的組1次或多次48 }49 }
運行結果:
javaRegex2 -- 匹配、切割、尋找