JAVARegex(二)

來源:互聯網
上載者:User

Regex:符合一定規則的運算式
作用:用於專門操作字串
特點:用於一些特點的符號來表示一些代碼操作。這樣的就簡化書寫
學習Regex就是學習一些特殊符號的使用
具體操作功能:
1.匹配:String 類的matches()
2.切割:String類的split()
3.替換:String類的replaceAll()
4.擷取:將字串中符合規則的字串取出
   (1)將Regex封裝成對象
   (2)讓正則對象和要操作的字串相關聯。
   (3)關聯後,擷取正則匹配引擎。
   (4)通過引擎對符合規則的字串進行操作,比如取出。
{n}指定的為剩餘的9位,不能多不能少;
{n,m}只能是n到接下來的m位,要匹配的字串可以多餘m位,但是不能少。
{n,}指定是n位元以上的所有的
"(.)\\1"按照疊詞完成切割,為了可以讓規則的結果重用,可以將規則封裝一個組。
       用()完成,組的出現都有編號。從1開始,
  想要使用已有的組可以通過 \n(n就是組的編號)的形式來擷取。
"\\\\"按照\\進行切割

" +":" +"出現一次或多次,用"."則必須用"\\."進行轉義

class  RegexDemo{public static void main(String[] args) {//demo();checkTel();//splitDemo("c:\\abc\\a.txt","\\\\");//按照\\進行切割        //splitDemo("erkktyqquiio","(.)\\1");         //replaceAllDemo("we54544456464sy455446dsdsa5451","\\d{0,}","#");}public static void demo(){  String str="56566565666666464";  //char[] buf=str.toCharArray();  String reg="[1-9][[0-9]&&[^a-zA-Z]]{4,14}";  boolean b=str.matches(reg);  System.out.println(b);}//匹配手機號 13xxx  15xxx  18xxxpublic static void checkTel(){   String tel="151723174065";   String telReg="1[358]\\d{3,}";   boolean flag=tel.matches(telReg);   System.out.println(flag);   }public static void splitDemo(String str,String reg){  //String str="zhangsan    lisi    wangwu";  //str="c:\\abc\\a.txt";  //String reg=" +";//  String[] arr=str.split(reg);    for(String s:arr) {       System.out.println(s);       }}public static void replaceAllDemo(String str,String reg,String newStr){   str=str.replaceAll(reg,newStr);   System.out.println(str);}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.