天天看點

14、Python 正規表達式(re)

一、正規表達式簡介

  • 正規表達式(regular expression)是一種用于比對字元串或者子串形式的強大邏輯表達式,在 Python 中的

    re 子產品

    提供了正規表達式的支援。
  • 正規表達式由一些一般字元和一些元字元組成
    • 一般字元包括:

      大小寫的字母和數字

      ,隻能比對自身
    • 元字元包括:

      . \ [...]、預定義字元集、數量詞、邊界比對、邏輯分組等

      ,具有特殊的含義
14、Python 正規表達式(re)

二、正規表達式的使用

  • 當我們在 Python 中使用正規表達式時,re 子產品内部會幹兩件事情:
    • 編譯正規表達式,如果正規表達式的字元串本身不合法,會報錯
    • 用編譯後的正規表達式去比對字元串
    • 如果一個正規表達式要重複使用幾千次,出于效率的考慮,我們可以預編譯該正規表達式,接下來重複使用時就不需要編譯這個步驟了,直接比對
  • p = re.compile(pattern, flags=0) # 預編譯

    • 用于将字元串形式的正規表達式編譯為 pattern 對象,第二個參數 flag 是比對模式,一般用不到
    • 預編譯時,pattern 最好加上 r 字首,這樣就不用考慮轉義的問題了
  • p.findall(string) or re.findall(pattern, string, flags=0) # 按照模式搜尋

    • 搜尋 string,以清單形式傳回全部能比對的子串
  • 代碼實踐
import re

p = re.compile(r'\d+')
p.findall('one11 two2three333 four4five55')
> ['11', '2', '333', '4', '55']

# 對于 * 和 + 這種預設貪婪的比對可以加上 ? 使之變為非貪婪比對
p = re.compile(r'\d+?')
p.findall('one11 two2three333 four4five55')
> ['1', '1', '2', '3', '3', '3', '4', '5', '5']

# 比對子串,用()表示:要提取的分組
p = re.compile(r'(\w+)@([\w.]+)')
str = 'purple [email protected], blah monkey [email protected] blah dishwasher'
p.findall(str)
> [('alice', 'jisuanke.com'), ('bob', 'abc.com')]

# 比對字元串
p = re.compile(r'\w+@[\w.]+')
re.findall(str)
> ['[email protected]', '[email protected]']
           

三、參考資料

1、正規表達式官方文檔

2、Python 正規表達式指南

3、廖雪峰 re 子產品介紹