javaRegex2 -- 匹配、切割、尋找

來源:互聯網
上載者:User

標籤: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 -- 匹配、切割、尋找

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.