JavaRegex學習教程_Regex

來源:互聯網
上載者:User

本教程旨在協助你駕馭JavaRegex,同時也協助我複習Regex。

什麼是Regex?

Regex定義了字串的模式。Regex可以用來搜尋、編輯或處理文本。Regex並不僅限於某一種語言,但是在每種語言中有細微的差別。JavaRegex和Perl的是最為相似的。

JavaRegex的類在 java.util.regex 包中,包括三個類:Pattern,Matcher PatternSyntaxException。

Pattern對象是Regex的已編譯版本。他沒有任何公用構造器,我們通過傳遞一個Regex參數給公用靜態方法 compile 來建立一個pattern對象。
Matcher是用來匹配輸入字串和建立的 pattern 對象的正則引擎對象。這個類沒有任何公用構造器,我們用patten對象的matcher方法,使用輸入字串作為參數來獲得一個Matcher對象。然後使用matches方法,通過返回的布爾值判斷輸入字串是否與正則匹配。
如果Regex文法不正確將拋出PatternSyntaxException異常。
讓我們在一個簡單的例子裡看看這些類是怎麼用的吧

package com.journaldev.util; import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexExamples {   public static void main(String[] args) {    // using pattern with flags    Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);    Matcher matcher = pattern.matcher("ABcabdAb");    // using Matcher find(), group(), start() and end() methods    while (matcher.find()) {      System.out.println("Found the text \"" + matcher.group()          + "\" starting at " + matcher.start()          + " index and ending at index " + matcher.end());    }     // using Pattern split() method    pattern = Pattern.compile("\\W");    String[] words = pattern.split("one@two#three:four$five");    for (String s : words) {      System.out.println("Split using Pattern.split(): " + s);    }     // using Matcher.replaceFirst() and replaceAll() methods    pattern = Pattern.compile("1*2");    matcher = pattern.matcher("11234512678");    System.out.println("Using replaceAll: " + matcher.replaceAll("_"));    System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));  } }

既然Regex總是和字串有關, Java 1.4對String類進行了擴充,提供了一個matches方法來匹配pattern。在方法內部使用Pattern和Matcher類來處理這些東西,但顯然這樣減少了代碼的行數。

Pattern類同樣有matches方法,可以讓正則和作為參數輸入的字串匹配,輸出布爾值結果。

下述的代碼可以將輸入字串和Regex進行匹配。

String str = "bbb";System.out.println("Using String matches method: "+str.matches(".bb"));System.out.println("Using Pattern matches method: "+Pattern.matches(".bb", str));

所以如果你的需要僅僅是檢查輸入字串是否和pattern匹配,你可以通過調用String的matches方法省下時間。只有當你需要操作輸入字串或者重用pattern的時候,你才需要使用Pattern和Matches類。

注意由正則定義的pattern是從左至右應用的,一旦一個原字元在一次匹配中使用過了,將不會再次使用。

例如,正則“121”只會匹配兩次字串“31212142121″,就像這樣“_121____121″。
Regex通用匹配符號

JavaRegex元字元

有兩種方法可以在Regex中像一般字元一樣使用元字元。

在元字元前添加反斜線(\)
將元字元置於\Q(開始引用)和\E(結束引用)間
Regex量詞

量詞指定了字元匹配的發生次數。

量詞可以和character classes和capturing group一起使用。

例如,[abc]+表示a,b或c出現一次或者多次。

 (abc)+表示capturing group “abc”出現一次或多次。我們即將討論capturing group。

Regexcapturing group

Capturing group是用來對付作為一個整體出現的多個字元。你可以通過使用()來建立一個group。輸入字串中和capturing group相匹配的部分將儲存在記憶體裡,並且可以通過使用Backreference調用。

你可以使用matcher.groupCount方法來獲得一個正則pattern中capturing groups的數目。例如((a)(bc))包含3個capturing groups; ((a)(bc)), (a) 和 (bc)。

你可以使用在Regex中使用Backreference,一個反斜線(\)接要調用的group號碼。

Capturing groups和Backreferences可能很令人困惑,所以我們通過一個例子來理解。

System.out.println(Pattern.matches("(\\w\\d)\\1", "a2a2")); //true  System.out.println(Pattern.matches("(\\w\\d)\\1", "a2b2")); //false  System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B2AB")); //true  System.out.println(Pattern.matches("(AB)(B\\d)\\2\\1", "ABB2B3AB")); //false

在第一個例子裡,啟動並執行時候第一個capturing group是(\w\d),在和輸入字串“a2a2″匹配的時候擷取“a2″並儲存到記憶體裡。因此\1是”a2”的引用,並且返回true。基於相同的原因,第二行代碼列印false。

試著自己理解第三行和第四行代碼。:)

現在我們來看看Pattern和Matcher類中一些重要的方法。

我們可以建立一個帶有標誌的Pattern對象。例如Pattern.CASE_INSENSITIVE可以進行大小寫不敏感的匹配。Pattern類同樣提供了和String類相似的split(String) 方法

Pattern類toString()方法返回被編譯成這個pattern的Regex字串。

Matcher類有start()和end()索引方法,他們可以顯示從輸入字串中匹配到的準確位置。

Matcher類同樣提供了字串操作方法replaceAll(String replacement)和replaceFirst(String replacement)。

現在我們在一個簡單的java類中看看這些函數是怎麼用的。

package com.journaldev.util; import java.util.regex.Matcher;import java.util.regex.Pattern; public class RegexExamples {   public static void main(String[] args) {    // using pattern with flags    Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);    Matcher matcher = pattern.matcher("ABcabdAb");    // using Matcher find(), group(), start() and end() methods    while (matcher.find()) {      System.out.println("Found the text \"" + matcher.group()          + "\" starting at " + matcher.start()          + " index and ending at index " + matcher.end());    }     // using Pattern split() method    pattern = Pattern.compile("\\W");    String[] words = pattern.split("one@two#three:four$five");    for (String s : words) {      System.out.println("Split using Pattern.split(): " + s);    }     // using Matcher.replaceFirst() and replaceAll() methods    pattern = Pattern.compile("1*2");    matcher = pattern.matcher("11234512678");    System.out.println("Using replaceAll: " + matcher.replaceAll("_"));    System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));  } }

上述程式的輸出:

Found the text "AB" starting at 0 index and ending at index 2Found the text "ab" starting at 3 index and ending at index 5Found the text "Ab" starting at 6 index and ending at index 8Split using Pattern.split(): oneSplit using Pattern.split(): twoSplit using Pattern.split(): threeSplit using Pattern.split(): fourSplit using Pattern.split(): fiveUsing replaceAll: _345_678Using replaceFirst: _34512678

這是不是一個很全面的JavaRegex學習教程,希望對大家的學習有所協助。

聯繫我們

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