<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 正則表達式教程 > 原文: [https://beginnersbook.com/2014/08/java-regex-tutorial/](https://beginnersbook.com/2014/08/java-regex-tutorial/) **正則表達式**用于定義可用于搜索,操作和編輯文本的字符串模式。這些表達式也稱為 **Regex** (正則表達式的簡寫形式)。 #### 讓我們舉個例子來更好地理解它: 在下面的示例中,正則表達式`.*book.*`用于搜索文本中字符串“book”的出現。 ```java import java.util.regex.*; class RegexExample1{ public static void main(String args[]){ String content = "This is Chaitanya " + "from Beginnersbook.com."; String pattern = ".*book.*"; boolean isMatch = Pattern.matches(pattern, content); System.out.println("The text contains 'book'? " + isMatch); } } ``` 輸出: ```java The text contains 'book'? true ``` 在本教程中,我們將學習如何定義模式以及如何使用它們。`java.util.regex` API(我們在處理 Regex 時需要導入的包)有兩個主要類: 1)`java.util.regex.Pattern` - 用于定義模式 2)`java.util.regex.Matcher` - 用于使用模式對文本執行匹配操作 ## `java.util.regex.Pattern`類: #### 1)`Pattern.matches()` 我們已經在上面的例子中看到過這種方法的用法,我們在給定的文本中搜索了字符串`"book"`。這是使用 Regex 在文本中搜索`String`的最簡單和最簡單的方法之一。 ```java String content = "This is a tutorial Website!"; String patternString = ".*tutorial.*"; boolean isMatch = Pattern.matches(patternString, content); System.out.println("The text contains 'tutorial'? " + isMatch); ``` 如您所見,我們使用`Pattern`類的`matches()`方法來搜索給定文本中的模式。模式`.*tutorial.*`在字符串`"tutorial"`的開頭和結尾允許零個或多個字符(表達式`.*`用于零個或多個字符)。 **限制**:通過這種方式,我們可以搜索文本中單個出現的模式。要匹配多次出現,您應該使用`Pattern.compile()`方法(在下一節中討論)。 #### 2)`Pattern.compile()` 在上面的例子中,我們在文本中搜索了一個字符串`"tutorial"`,這是一個區分大小寫的搜索,但是如果你想進行大小寫不敏感搜索或者想要多次搜索,那么你可能需要在用文本搜索之前,先使用`Pattern.compile()`。這就是這種方法可以用于這種情況的方法。 ```java String content = "This is a tutorial Website!"; String patternString = ".*tuToRiAl."; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); ``` 這里我們使用了一個標志`Pattern.CASE_INSENSITIVE`來進行不區分大小寫的搜索,還有其他幾個標志可以用于不同的目的。要閱讀有關此類標志的更多信息,[請參閱此文檔](https://docs.oracle.com/javase/tutorial/essential/regex/pattern.html)。 **現在**:我們已經獲得了一個`Pattern`實例,但是如何匹配呢?為此,我們需要一個`Matcher`實例,我們可以使用`Pattern.matcher()`方法。讓我們討論一下。 #### 3)`Pattern.matcher()`方法 在上一節中,我們學習了如何使用`compile()`方法獲取`Pattern`實例。在這里,我們將學習如何使用`matcher()`方法從`Pattern`實例獲取`Matcher`實例。 ```java String content = "This is a tutorial Website!"; String patternString = ".*tuToRiAl.*"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); Matcher matcher = pattern.matcher(content); boolean isMatched = matcher.matches(); System.out.println("Is it a Match?" + isMatched); ``` 輸出: ```java Is it a Match?true ``` #### 4)`Pattern.split()` 要根據分隔符將文本拆分為多個字符串(這里使用**正則表達式**指定分隔符),我們可以使用`Pattern.split()`方法。這是如何做到的。 ```java import java.util.regex.*; class RegexExample2{ public static void main(String args[]){ String text = "ThisIsChaitanya.ItISMyWebsite"; // Pattern for delimiter String patternString = "is"; Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE); String[] myStrings = pattern.split(text); for(String temp: myStrings){ System.out.println(temp); } System.out.println("Number of split strings: "+myStrings.length); }} ``` 輸出: ```java Th Chaitanya.It MyWebsite Number of split strings: 4 ``` 第二個拆分字符串在輸出中為`null`。 ## `java.util.regex.Matcher`類 我們已經討論過上面的`Matcher`類了。讓我們回憶一下: #### 創建`Matcher`實例 ```java String content = "Some text"; String patternString = ".*somestring.*"; Pattern pattern = Pattern.compile(patternString); Matcher matcher = pattern.matcher(content); ``` #### 主要方法 `matches()`:它在創建 Matcher 實例時將正則表達式與傳遞給`Pattern.matcher()`方法的整個文本進行匹配。 ```java ... Matcher matcher = pattern.matcher(content); boolean isMatch = matcher.matches(); ``` `lookingAt()`:類似于`matches()`方法,只是它匹配正則表達式只對著文本的開頭,而`matches()`搜索整個文本。 `find()`:搜索文本中正則表達式的出現次數。主要用于搜索多次出現的情況。 `start()`和`end()`:這兩種方法通常與`find()`方法一起使用。它們用于獲取使用`find()`方法找到的匹配項的開始和結束索引。 #### 讓我們舉個例子使用`Matcher`方法來找出多次出現: ```java package beginnersbook.com; import java.util.regex.*; class RegexExampleMatcher{ public static void main(String args[]){ String content = "ZZZ AA PP AA QQQ AAA ZZ"; String string = "AA"; Pattern pattern = Pattern.compile(string); Matcher matcher = pattern.matcher(content); while(matcher.find()) { System.out.println("Found at: "+ matcher.start() + " - " + matcher.end()); } } } ``` 輸出: ```java Found at: 4 - 6 Found at: 10 - 12 Found at: 17 - 19 ``` 現在我們熟悉`Pattern`和`Matcher`類以及將正則表達式與文本匹配的過程。讓我們看一下我們定義正則表達式的各種選項: #### 1)字符串字面值 假設您只想在文本中搜索特定字符串,例如“abc”然后我們可以簡單地編寫這樣的代碼:這里的文本和正則表達式都是相同的。 `Pattern.matches("abc", "abc")` #### 2)字符類 字符類將輸入文本中的單個字符與字符類中的多個允許字符進行匹配。例如`[Cc]haitanya`將匹配所有出現的字符串`"chaitanya"`,帶有小寫或大寫`C`。更多例子: `Pattern.matches("[pqr]", "abcd");`它會給出錯誤,因為文中沒有`p`,`q`或`r` `Pattern.matches("[pqr]", "r");`當找到`r`時返回`true` `Pattern.matches("[pqr]", "pq");`返回`false`,因為其中任何一個都可以在文本中不是兩個。 以下是各種字符類構造的完整列表: `[abc]`:如果文本中包含其中一個(`a`,`b`或`c`)且只有一次,它將與文本匹配。 `[^abc]`:除`a`,`b`或`c`以外的任何單個字符(`^`表示否定) `[a-zA-Z]`:`a`到`z`,或`A`到`Z`,包括(范圍) `[a-d[m-p]]`:`a`到`d`,或`m`到`p`:`[a-dm-p]`(聯合) `[a-z&&[def]]`:它們中的任何一個(`d`,`e`或`f`) `[a-z&&[^bc]]`:`a`到`z`,除了`b`和`c`:`[ad-z]`(減法) `[a-z&&[^m-p]]`:`a`到`z`,除了`m`到`p`:`[a-lq-z]`(減法) #### 預定義字符類 - 元字符 這些就像在編寫正則表達式時可以使用的短代碼。 ```java Construct Description . -> Any character (may or may not match line terminators) \d -> A digit: [0-9] \D -> A non-digit: [^0-9] \s -> A whitespace character: [ \t\n\x0B\f\r] \S -> A non-whitespace character: [^\s] \w -> A word character: [a-zA-Z_0-9] \W -> A non-word character: [^\w] ``` 對于例如 `Pattern.matches("\\d", "1");`將返回`true` `Pattern.matches("\\D", "z");`返回`true` `Pattern.matches(".p", "qp");`返回`true`,點(`.`)代表任何字符 #### 邊界匹配器 ```java ^ Matches the beginning of a line. $ Matches then end of a line. \b Matches a word boundary. \B Matches a non-word boundary. \A Matches the beginning of the input text. \G Matches the end of the previous match \Z Matches the end of the input text except the final terminator if any. \z Matches the end of the input text. ``` 例如 `Pattern.matches("^Hello$", "Hello")`:返回`true`,以`Hello`開始和結束 `Pattern.matches("^Hello$", "Namaste! Hello")`:返回`false`,不以`Hello`開始 `Pattern.matches("^Hello$", "Hello Namaste!")`:返回`false`,不以`Hello`結束 #### 量詞 ```java Greedy Reluctant Possessive Matches X? X?? X?+ Matches X once, or not at all (0 or 1 time). X* X*? X*+ Matches X zero or more times. X+ X+? X++ Matches X one or more times. X{n} X{n}? X{n}+ Matches X exactly n times. X{n,} X{n,}? X{n,}+ Matches X at least n times. X{n, m) X{n, m)? X{n, m)+ Matches X at least n time, but at most m times. ``` #### 幾個例子 ```java import java.util.regex.*; class RegexExample{ public static void main(String args[]){ // It would return true if string matches exactly "tom" System.out.println( Pattern.matches("tom", "Tom")); //False /* returns true if the string matches exactly * "tom" or "Tom" */ System.out.println( Pattern.matches("[Tt]om", "Tom")); //True System.out.println( Pattern.matches("[Tt]om", "Tom")); //True /* Returns true if the string matches exactly "tim" * or "Tim" or "jin" or "Jin" */ System.out.println( Pattern.matches("[tT]im|[jJ]in", "Tim"));//True System.out.println( Pattern.matches("[tT]im|[jJ]in", "jin"));//True /* returns true if the string contains "abc" at * any place */ System.out.println( Pattern.matches(".*abc.*", "deabcpq"));//True /* returns true if the string does not have a * number at the beginning */ System.out.println( Pattern.matches("^[^\\d].*", "123abc")); //False System.out.println( Pattern.matches("^[^\\d].*", "abc123")); //True // returns true if the string contains of three letters System.out.println( Pattern.matches("[a-zA-Z][a-zA-Z][a-zA-Z]", "aPz"));//True System.out.println( Pattern.matches("[a-zA-Z][a-zA-Z][a-zA-Z]", "aAA"));//True System.out.println( Pattern.matches("[a-zA-Z][a-zA-Z][a-zA-Z]", "apZx"));//False // returns true if the string contains 0 or more non-digits System.out.println( Pattern.matches("\\D*", "abcde")); //True System.out.println( Pattern.matches("\\D*", "abcde123")); //False /* Boundary Matchers example * ^ denotes start of the line * $ denotes end of the line */ System.out.println( Pattern.matches("^This$", "This is Chaitanya")); //False System.out.println( Pattern.matches("^This$", "This")); //True System.out.println( Pattern.matches("^This$", "Is This Chaitanya")); //False } } ``` #### 參考 [正則表達式 - Javadoc](https://docs.oracle.com/javase/tutorial/essential/regex/)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看