4.熟悉Java基本類庫系列——Java Regex類庫

來源:互聯網
上載者:User

標籤:

Regex文法結構圖: 

JavaRegex類庫結構圖:

 

Java典型例子

 1、String類 matches()方法

判斷字串是否符合特定Regex

@Test public void testRegex(){String regex = ".*\\d{3}.*";String str1 = "11tec34";String str2 = "285dffd";String str3 = "bac7736db";//輸出:false, true, trueSystem.out.println(str1.matches(regex) + "," + str2.matches(regex) + "," + str3.matches(regex));}

2、String類 split()方法

用Regex分割字串

@Test public void testRegex2(){String input = "hello3world8my9name1is5jacket";String regex = "\\d";  //以數字作為分隔字元String strs[] = input.split(regex);//輸出:hello world my name is jacketfor(String str : strs){System.out.print(str + " ");} System.out.println();input = "hellodogworlddogmydognamedogisdogjacket";regex = "dog";  //以"dog"字元作為分隔字元strs = input.split(regex);//輸出:hello world my name is jacketfor(String str : strs){System.out.print(str + " ");} }

3、String類 replace()方法

用Regex替換字元

@Test public void testRegex3(){String input = "hello3world8my9name1is5jacket";String regex = "\\d";  //以數字作為分隔字元String firstStr = input.replaceFirst(regex, ":"); //只替換第一個匹配的字元String allStr = input.replaceAll(regex, ":");  //替換所有匹配的字元//輸出://hello:world8my9name1is5jacket//hello:world:my:name:is:jacketSystem.out.println(firstStr);System.out.println(allStr);}

4、Pattern.matches() 靜態方法

判斷字串是否符合Regex,等同於String類的matches()方法

@Test public void testRegex4(){String regex1 = "\\bdog\\b";String regex2 = ".*\\bdog\\b.*";String input = "dog dog dog doggie dogg";//輸出:false,trueSystem.out.println(Pattern.matches(regex1, input) + "," + Pattern.matches(regex2, input));  }

5、Pattern類 split()方法

根據Regex分割字串,等同於String類的split()方法

//6.split() 分割字串  -> 等同於String的split()方法@Test public void testRegex6(){String regex = "\\d";String input = "hello3world5hello8java";Pattern p = Pattern.compile(regex);String strs[] = p.split(input);//輸出:hello world hello java for(String str : strs){System.out.print(str + " ");}}

6、Pattern.quote() 靜態方法

擷取匹配此字串的Regex

@Test public void testRegex6(){//例子1String input = ".";String regex = Pattern.quote(input);boolean flag = Pattern.matches(regex, input);//輸出:\Q353434\EtrueSystem.out.println(regex);System.out.println(flag);//例子2input = "test.test";String errorOutput = input.replaceAll(".", "/");//輸出://///////System.out.println(errorOutput);//例子3String correctOutput = input.replaceAll(Pattern.quote("."), "/");//輸出:test/testSystem.out.println(correctOutput);}

7、Matcher類 find()方法,start()方法,end()方法

@Test public void testRegex7(){//m.start()   m.end()  String regex = "\\bdog\\b"; String input = "dog dog dog doggie dogg"; Pattern p = Pattern.compile(regex);     Matcher m = p.matcher(input);        // 獲得匹配器對象     int count = 0;     while (m.find()) {            count++;            //Match number 1,start(): 0,end(): 3           //Match number 2,start(): 4,end(): 7           //Match number 3,start(): 8,end(): 11           System.out.print("Match number " + count);            System.out.print(",start(): " + m.start());            System.out.println(",end(): " + m.end());     } }

8、Matcher類 find(int index)方法,start(int index),end(int index)

@Test public void testRegex8(){//m.start()   m.end()  String regex = "\\bdog\\b"; String input = "dog dog dog doggie dogg"; Pattern p = Pattern.compile(regex);       Matcher m = p.matcher(input);        // 獲得匹配器對象        //m.find(int start)    //輸出:start(): 0,end(): 3    //start(): 4,end(): 7    m.find(0);  //從要匹配的字串的第幾個字元開始尋找    System.out.print("start(): " + m.start());     System.out.println("end(): " + m.end());     m.find();    System.out.print("start(): " + m.start());     System.out.println("end(): " + m.end());         //m.find(int start)    //輸出:start(): 4,end(): 7    //start(): 8,end(): 11    m.find(4);      System.out.print("start(): " + m.start());     System.out.println("end(): " + m.end());     m.find();    System.out.print("start(): " + m.start());     System.out.println("end(): " + m.end());         //m.start(int group)m.end(int group)    m.find(0);//    int firstStartGroupIndex = m.start(0);    System.out.println(firstStartGroupIndex); }

9、Matcher類 lookingAt()方法,matches()方法

判斷字串是否匹配特定的Regex,lookingAt()方法不要求全部匹配,而matches()方法要求全部匹配

@Test public void testRegex9(){String regex = "foo"; String str = "fooooooooooooooooo";         Pattern pattern = Pattern.compile(regex);         Matcher matcher = pattern.matcher(str);          System.out.println("Current regex is: " + regex);         System.out.println("Current str is: " + str);          System.out.println("lookingAt(): " + matcher.lookingAt());  //true         System.out.println("matches(): " + matcher.matches()); //false,因為matches要求全部匹配}

 

此外還有其他的Matcher類的方法未整理,

//還有Matcher類的其他方法未整理:

//1.group(int group)方法

//2.appendReplacement() / appendTail() / replaceAll() / replaceFirst() / quoteReplacement()

//99.Matcher類的find()方法,start()方法,end()方法

   

更多詳細的Regex博文可以參考:

微軟官方文檔:https://msdn.microsoft.com/zh-cn/library/ae5bf541(v=vs.80).aspx

一個很好的Regex教程:http://www.java3z.com/cwbwebhome/article/article8/Regex/Java.Regex.Tutorial.html#reg7

 

4.熟悉Java基本類庫系列——Java Regex類庫

聯繫我們

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