<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國際加速解決方案。 廣告
                # Python 正則表達式 > 原文: [https://www.programiz.com/python-programming/regex](https://www.programiz.com/python-programming/regex) #### 在本教程中,您將學習正則表達式(RegEx),并使用 Python 的`re`模塊與 RegEx 一起使用(在示例的幫助下)。 正則表達式(RegEx)是定義搜索模式的字符序列。 例如, ```py ^a...s$ ``` 上面的代碼定義了 RegEx 模式。 模式為從`a`到`s`的任何五個字母的字符串。 使用 RegEx 定義的模式可用于與字符串匹配。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `^a...s$` | `abs` | 沒有匹配 | | | `alias` | 匹配 | | | `abyss` | 匹配 | | | `Alias` | 沒有匹配 | | | `An abacus` | 沒有匹配 | * * * Python 有一個名為`re`的模塊可與 RegEx 一起使用。 這是一個例子: ```py import re pattern = '^a...s$' test_string = 'abyss' result = re.match(pattern, test_string) if result: print("Search successful.") else: print("Search unsuccessful.") ``` 在這里,我們使用`re.match()`函數在`test_string`中搜索`pattern`。 如果搜索成功,該方法將返回一個匹配對象。 如果不是,則返回`None`。 * * * `re`模塊中定義了其他一些函數,可與 RegEx 一起使用。 在探討之前,讓我們學習正則表達式本身。 如果您已經了解 RegEx 的基礎知識,請跳至 [Python RegEx](#python-regex)。 * * * ## 使用 RegEx 指定模式 為了指定正則表達式,使用了元字符。 在上面的示例中,`^`和`$`是元字符。 * * * ### 元字符 元字符是 RegEx 引擎以特殊方式解釋的字符。 以下是元字符列表: ```py [] . ^ $ + ? {} () \ | ``` * * * `[]` - **方括號** 方括號指定您要匹配的一組字符。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `[abc]` | `a` | 1 個匹配 | | | `ac` | 2 個匹配 | | | `Hey Jude` | 沒有匹配 | | | `abc de ca` | 5 個匹配 | 在這里,如果您要匹配的字符串包含`a`,`b`或`c`中的任何一個,則`[abc]`將匹配。 您也可以使用方括號內的`-`指定字符范圍。 * `[a-e]`與`[abcde]`相同。 * `[1-4]`與`[1234]`相同。 * `[0-39]`與`[01239]`相同。 您可以在方括號的開頭使用尖號`^`符號來補充(反轉)字符集。 * `[^abc]`表示除`a`或`b`或`c`之外的任何字符。 * `[^0-9]`表示任何非數字字符。 * * * `.` - **句號** 句點匹配任何單個字符(換行符`'\n'`除外)。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `..` | `a` | 沒有匹配 | | | `ac` | 1 個匹配 | | | `acd` | 1 個匹配 | | | `acde` | 2 個匹配(包含 4 個字符) | * * * `^` - **脫字符** 插入符號`^`用于檢查字符串**是否以某個字符開頭**。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `^a` | `a` | 1 個匹配 | | `abc` | 1 個匹配 | | `bac` | 沒有匹配 | | `^ab` | `abc` | 1 個匹配 | | `acb` | 沒有匹配(以`a`開頭,但之后沒有`b`) | * * * `$` - **美元** 美元符號`$`用于檢查字符串**是否以某個字符結束**。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `a$` | `a` | 1 個匹配 | | `formula` | 1 個匹配 | | `cab` | 沒有匹配 | * * * `*` - **星號** 星形符號`*`匹配**模式的零次或多次出現**。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `ma*n` | `mn` | 1 個匹配 | | `man` | 1 個匹配 | | `maaan` | 1 個匹配 | | `main` | 沒有匹配(`a`之后沒有`n`) | | `woman` | 1 個匹配 | * * * `+`- **加號** 加號`+`**匹配左側的模式的一個或多個出現**。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `ma+n` | `mn` | 沒有匹配(沒有`a`字符) | | `man` | 1 個匹配 | | `maaan` | 1 個匹配 | | `main` | 沒有匹配(`a`后跟`n`) | | `woman` | 1 個匹配 | * * * `?` - **問號** 問號符號`?`匹配**模式的零或一次出現**。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `ma?n` | `mn` | 1 個匹配 | | `man` | 1 個匹配 | | `maaan` | 沒有匹配(一個以上`a`字符) | | `main` | 沒有匹配(`a`之后沒有`n`) | | `woman` | 1 個匹配 | * * * `{}` - **大括號** 考慮以下代碼:`{n,m}`。 這意味著至少`n`,并且最多`m`個重復的模式留給它。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `a{2,3}` | `abc dat` | 沒有匹配 | | `abc daat` | 1 個匹配(在`d<u>aa</u>t`) | | `aabc daaat` | 2 個匹配(在`<u>aa</u>bc`和`d<u>aaa</u>t`) | | `aabc daaaat` | 2 個匹配(在`<u>aa</u>bc`和`d<u>aaa</u>at`) | 讓我們再嘗試一個示例。 此 RegEx `[0-9]{2, 4}`匹配至少 2 位但不超過 4 位 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `[0-9]{2,4}` | `ab123csde` | 1 個匹配(在`ab<u>123</u>csde`) | | `12 and 345673` | 3 個匹配(`<u>12</u>`,`<u>3456</u>`,`<u>73</u>`) | | `1 and 2` | 沒有匹配 | * * * `|` - **替代項** 豎線`|`用于交替(`or`運算符)。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `a&#124;b` | `cde` | 沒有匹配 | | `ade` | 1 個匹配(在`<u>a</u>de`匹配) | | `acdbea` | 3 個匹配(在`<u>a</u>cd<u>b</u>e<u>a</u>`) | 在此,`a|b`匹配包含`a`或`b`的任何字符串 * * * `()` - **分組** 括號`()`用于對子模式進行分組。 例如,`(a|b|c)xz`匹配與`a`或`b`或`c`匹配的任何字符串,后跟`xz` | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `(a&#124;b&#124;c)xz` | `ab xz` | 沒有匹配 | | `abxz` | 1 個匹配(在`a<u>bxz</u>`匹配) | | `axz cabxz` | 2 個匹配(在`<u>axz</u>bc ca<u>bxz</u>`) | * * * `\` - **反斜線** 反沖`\`用于轉義包括所有元字符在內的各種字符。 例如, 如果字符串包含`$`后跟`a`,則`\$a`匹配。 在這里,`$`不是由 RegEx 引擎以特殊方式解釋的。 如果不確定某個字符是否具有特殊含義,可以在其前面放置`\`。 這樣可以確保不對字符進行特殊處理。 * * * **特殊序列** 特殊序列使常用模式更易于編寫。 以下是特殊序列的列表: `\A` - 如果指定字符在字符串的開頭,則匹配。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\Athe` | `the sun` | 匹配 | | `In the sun` | 沒有匹配 | * * * `\b` - 如果指定字符在單詞的開頭或結尾,則匹配。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\bfoo` | `football` | 匹配 | | `a football` | 匹配 | | `afootball` | 沒有匹配 | | `foo\b` | `the foo` | 匹配 | | `the afoo test` | 匹配 | | `the afootest` | 沒有匹配 | * * * `\B` - 與`\b`相反。 如果指定字符不是單詞開頭或結尾,則匹配。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\Bfoo` | `football` | 沒有匹配 | | `a football` | 沒有匹配 | | `afootball` | 匹配 | | `foo\B` | `the foo` | 沒有匹配 | | `the afoo test` | 沒有匹配 | | `the afootest` | 匹配 | * * * `\d` - 匹配任何十進制數字。 相當于`[0-9]` | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\d` | `12abc3` | 3 個匹配(在`<u>12</u>abc<u>3</u>`) | | `Python` | 沒有匹配 | * * * `\D` - 匹配任何非十進制數字。 相當于`[^0-9]` | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\D` | `1ab34"50` | 3 個匹配(在`1<u>ab</u>34<u>"</u>50`) | | `1345` | 沒有匹配 | * * * `\s` - 匹配字符串包含任何空格字符的地方。 等效于`[ \t\n\r\f\v]`。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\s` | `Python RegEx` | 1 個匹配 | | `PythonRegEx` | 沒有匹配 | * * * `\S` - 匹配字符串包含任何非空白字符的地方。 等效于`[^ \t\n\r\f\v]`。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\S` | `a b` | 2 個匹配(在`<u>a</u> <u>b</u>`) | | | 沒有匹配 | * * * `\w` - 匹配任何字母數字字符(數字和字母)。 等效于`[a-zA-Z0-9_]`。 順便說一下,下劃線`_`也被認為是字母數字字符。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\w` | `12&": ;c` | 3 個匹配(在`<u>12</u>&": ;<u>c</u>`) | | `%"> !` | 沒有匹配 | * * * `\W` - 匹配任何非字母數字字符。 相當于`[^a-zA-Z0-9_]` | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `\W` | `1a2%c` | 1 個匹配(在`1<u>a</u>2<u>%</u>c`) | | `Python` | 沒有匹配 | * * * `\Z` - 如果指定字符在字符串的末尾,則匹配。 | 表達式 | 字符串 | 是否匹配 | | --- | --- | --- | | `Python\Z` | `I like Python` | 1 個匹配 | | `I like Python Programming` | 沒有匹配 | | `Python is fun.` | 沒有匹配 | * * * **提示**:要構建和測試正則表達式,可以使用 RegEx 測試器工具,例如 [regex101](https://regex101.com/ "RegEx tester") 。 該工具不僅可以幫助您創建正則表達式,還可以幫助您學習它。 現在,您了解了 RegEx 的基礎知識,讓我們討論如何在 Python 代碼中使用 RegEx。 * * * ## Python RegEx Python 有一個名為`re`的模塊可用于正則表達式。 要使用它,我們需要導入模塊。 ```py import re ``` 該模塊定義了一些可與 RegEx 一起使用的函數和常量。 * * * ## `re.findall()` `re.findall()`方法返回包含所有匹配項的字符串列表。 * * * ### 示例 1:`re.findall()` ```py # Program to extract numbers from a string import re string = 'hello 12 hi 89\. Howdy 34' pattern = '\d+' result = re.findall(pattern, string) print(result) # Output: ['12', '89', '34'] ``` 如果找不到該模式,則`re.findall()`返回一個空列表。 * * * ## `re.split()` `re.split`方法在存在匹配項的地方拆分字符串,并返回發生拆分的字符串列表。 * * * ### 示例 2:`re.split()` ```py import re string = 'Twelve:12 Eighty nine:89.' pattern = '\d+' result = re.split(pattern, string) print(result) # Output: ['Twelve:', ' Eighty nine:', '.'] ``` 如果找不到該模式,則`re.split()`返回一個包含原始字符串的列表。 * * * 您可以將`maxsplit`參數傳遞給`re.split()`方法。 這是將要發生的最大拆分次數。 ```py import re string = 'Twelve:12 Eighty nine:89 Nine:9.' pattern = '\d+' # maxsplit = 1 # split only at the first occurrence result = re.split(pattern, string, 1) print(result) # Output: ['Twelve:', ' Eighty nine:89 Nine:9.'] ``` 順便說一下,`maxsplit`的默認值為 0; 意味著所有可能的分裂。 * * * ## `re.sub()` `re.sub()`的語法為: ```py re.sub(pattern, replace, string) ``` 該方法返回一個字符串,其中匹配的匹配項被`replace`變量的內容替換。 * * * ### 示例 3:`re.sub()` ```py # Program to remove all whitespaces import re # multiline string string = 'abc 12\ de 23 \n f45 6' # matches all whitespace characters pattern = '\s+' # empty string replace = '' new_string = re.sub(pattern, replace, string) print(new_string) # Output: abc12de23f456 ``` 如果找不到該模式,則`re.sub()`返回原始字符串。 * * * 您可以將`count`作為第四個參數傳遞給`re.sub()`方法。 如果省略,則結果為 0。這將替換所有出現的事件。 ```py import re # multiline string string = 'abc 12\ de 23 \n f45 6' # matches all whitespace characters pattern = '\s+' replace = '' new_string = re.sub(r'\s+', replace, string, 1) print(new_string) # Output: # abc12de 23 # f45 6 ``` * * * ## `re.subn()` `re.subn()`與`re.sub()`相似,但期望它返回 2 個項目的元組,其中包含新字符串和進行的替換數目。 * * * ### 示例 4:`re.subn()` ```py # Program to remove all whitespaces import re # multiline string string = 'abc 12\ de 23 \n f45 6' # matches all whitespace characters pattern = '\s+' # empty string replace = '' new_string = re.subn(pattern, replace, string) print(new_string) # Output: ('abc12de23f456', 4) ``` * * * ## `re.search()` `re.search()`方法采用兩個參數:模式和字符串。 該方法查找 RegEx 模式與字符串匹配的第一個位置。 如果搜索成功,則`re.search()`返回一個匹配對象。 如果不是,則返回`None`。 ```py match = re.search(pattern, str) ``` * * * ### 示例 5:`re.search()` ```py import re string = "Python is fun" # check if 'Python' is at the beginning match = re.search('\APython', string) if match: print("pattern found inside the string") else: print("pattern not found") # Output: pattern found inside the string ``` 在此,`match`包含一個匹配對象。 * * * ## 匹配對象 您可以使用[`dir()`](/python-programming/methods/built-in/dir)函數獲取匹配對象的方法和屬性。 匹配對象的一些常用方法和屬性是: * * * ### `match.group()` `group()`方法返回字符串中匹配的部分。 ### 示例 6:匹配對象 ```py import re string = '39801 356, 2102 1111' # Three digit number followed by space followed by two digit number pattern = '(\d{3}) (\d{2})' # match variable contains a Match object. match = re.search(pattern, string) if match: print(match.group()) else: print("pattern not found") # Output: 801 35 ``` 在此,`match`變量包含一個匹配對象。 我們的模式`(\d{3}) (\d{2})`具有兩個子組`(\d{3})`和`(\d{2})`。 您可以獲取這些帶括號的子組的字符串的一部分。 這是如何做: ```py >>> match.group(1) '801' >>> match.group(2) '35' >>> match.group(1, 2) ('801', '35') >>> match.groups() ('801', '35') ``` * * * ### `match.start()`,`match.end()`和`match.span()` `start()`函數返回匹配的子字符串的開頭的索引。 同樣,`end()`返回匹配的子字符串的結束索引。 ```py >>> match.start() 2 >>> match.end() 8 ``` `span()`函數返回一個包含匹配部分的開始和結束索引的元組。 ```py >>> match.span() (2, 8) ``` * * * ### `match.re`和`match.string` 匹配對象的`re`屬性返回正則表達式對象。 同樣,`string`屬性返回傳遞的字符串。 ```py >>> match.re re.compile('(\\d{3}) (\\d{2})') >>> match.string '39801 356, 2102 1111' ``` * * * 我們已經介紹了`re`模塊中定義的所有常用方法。 如果您想了解更多信息,請訪問 [Python 3 `re`模塊](https://docs.python.org/3/library/re.html)。 * * * ### 在 RegEx 之前使用`r`前綴 在正則表達式前使用`r`或`R`前綴時,表示原始字符串。 例如,`'\n'`是換行,而`r'\n'`表示兩個字符:反斜杠`\`后跟`n`。 反沖`\`用于轉義包括所有元字符在內的各種字符。 但是,使用`r`前綴會使`\`被視為正常字符。 * * * ### 示例 7:使用`r`前綴的原始字符串 ```py import re string = '\n and \r are escape sequences.' result = re.findall(r'[\n\r]', string) print(result) # Output: ['\n', '\r'] ```
                  <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>

                              哎呀哎呀视频在线观看