1. 程式人生 > >python3--正則表達式

python3--正則表達式

hit 實例 nor dbo broadcast 特殊 log 手機 reat

python3--正則表達式

語法:

import re #導入模塊名
 
p = re.compile("^[0-9]")  #生成要匹配的正則對象 , ^代表從開頭匹配,[0-9]代表匹配0至9的任意一個數字, 所以這裏的意思是對傳進來的字符串進行匹配,如果這個字符串的開頭第一個字符是數字,就代表匹配上了
 
m = p.match(‘14534Abc‘)   #按上面生成的正則對象 去匹配 字符串, 如果能匹配成功,這個m就會有值,否則m為None<br><br>if m: #不為空代表匹配上了
  print(m.group())    #m.group()返回匹配上的結果,此處為1,因為匹配上的是1這個字符
else:
  print("doesn‘t match.")

上面的第2 和第3行也可以合並成一行來寫:

m = p.match("^[0-9]",‘14534Abc‘)

效果是一樣的,區別在於,第一種方式是提前對要匹配的格式進行了編譯(對匹配公式進行解析),這樣再去匹配的時候就不用在編譯匹配的格式,第2種簡寫是每次匹配的時候 都 要進行一次匹配公式的編譯,所以,如果你需要從一個5w行的文件中匹配出所有以數字開頭的行,建議先把正則公式進行編譯再匹配,這樣速度會快點。

匹配格式

模式描述
^ 匹配字符串的開頭
$ 匹配字符串的末尾。
. 匹配任意字符,除了換行符,當re.DOTALL標記被指定時,則可以匹配包括換行符的任意字符。
[...]
用來表示一組字符,單獨列出:[amk] 匹配 ‘a‘,‘m‘或‘k‘
[^...] 不在[]中的字符:[^abc] 匹配除了a,b,c之外的字符。
re* 匹配0個或多個的表達式。
re+ 匹配1個或多個的表達式。
re? 匹配0個或1個由前面的正則表達式定義的片段,非貪婪方式
re{ n}
re{ n,} 精確匹配n個前面表達式。
re{ n, m} 匹配 n 到 m 次由前面的正則表達式定義的片段,貪婪方式
a| b 匹配a或b
(re) G匹配括號內的表達式,也表示一個組
(?imx) 正則表達式包含三種可選標誌:i, m, 或 x 。只影響括號中的區域。
(?-imx) 正則表達式關閉 i, m, 或 x 可選標誌。只影響括號中的區域。
(?: re) 類似 (...), 但是不表示一個組
(?imx: re) 在括號中使用i, m, 或 x 可選標誌
(?-imx: re) 在括號中不使用i, m, 或 x 可選標誌
(?#...) 註釋.
(?= re) 前向肯定界定符。如果所含正則表達式,以 ... 表示,在當前位置成功匹配時成功,否則失敗。但一旦所含表達式已經嘗試,匹配引擎根本沒有提高;模式的剩余部分還要嘗試界定符的右邊。
(?! re) 前向否定界定符。與肯定界定符相反;當所含表達式不能在字符串當前位置匹配時成功
(?> re) 匹配的獨立模式,省去回溯。
\w 匹配字母數字
\W 匹配非字母數字
\s 匹配任意空白字符,等價於 [\t\n\r\f].
\S 匹配任意非空字符
\d 匹配任意數字,等價於 [0-9].
\D 匹配任意非數字
\A 匹配字符串開始
\Z 匹配字符串結束,如果是存在換行,只匹配到換行前的結束字符串。c
\z 匹配字符串結束
\G 匹配最後匹配完成的位置。
\b 匹配一個單詞邊界,也就是指單詞和空格間的位置。例如, ‘er\b‘ 可以匹配"never" 中的 ‘er‘,但不能匹配 "verb" 中的 ‘er‘。
\B 匹配非單詞邊界。‘er\B‘ 能匹配 "verb" 中的 ‘er‘,但不能匹配 "never" 中的 ‘er‘。
\n, \t, 等. 匹配一個換行符。匹配一個制表符。等
\1...\9 匹配第n個分組的子表達式。
\10 匹配第n個分組的子表達式,如果它經匹配。否則指的是八進制字符碼的表達式。

正則表達式常用5種操作

re.match(pattern, string)     # 從頭匹配
re.search(pattern, string)    # 匹配整個字符串,直到找到一個匹配
re.split()            # 將匹配到的格式當做分割點對字符串分割成列表

>>>m = re.split("[0-9]", "alex1rain2jack3helen rachel8")
>>>print(m)

輸出: [‘alex‘, ‘rain‘, ‘jack‘, ‘helen rachel‘, ‘‘]

re.findall()          # 找到所有要匹配的字符並返回列表格式

>>>m = re.findall("[0-9]", "alex1rain2jack3helen rachel8")
>>>print(m)<br>

輸出:[‘1‘, ‘2‘, ‘3‘, ‘8‘]

re.sub(pattern, repl, string, count,flag)    # 替換匹配到的字符

m=re.sub("[0-9]","|", "alex1rain2jack3helen rachel8",count=2 )
print(m)

輸出:alex|rain|jack3helen rachel8

正則表達式實例

字符匹配

實例描述
python 匹配 "python".

字符類

實例描述
[Pp]ython 匹配 "Python" 或 "python"
rub[ye] 匹配 "ruby" 或 "rube"
[aeiou] 匹配中括號內的任意一個字母
[0-9] 匹配任何數字。類似於 [0123456789]
[a-z] 匹配任何小寫字母
[A-Z] 匹配任何大寫字母
[a-zA-Z0-9] 匹配任何字母及數字
[^aeiou] 除了aeiou字母以外的所有字符
[^0-9] 匹配除了數字外的字符

特殊字符類

實例描述
. 匹配除 "\n" 之外的任何單個字符。要匹配包括 ‘\n‘ 在內的任何字符,請使用象 ‘[.\n]‘ 的模式。
\d 匹配一個數字字符。等價於 [0-9]。
\D 匹配一個非數字字符。等價於 [^0-9]。
\s 匹配任何空白字符,包括空格、制表符、換頁符等等。等價於 [ \f\n\r\t\v]。
\S 匹配任何非空白字符。等價於 [^ \f\n\r\t\v]。
\w 匹配包括下劃線的任何單詞字符。等價於‘[A-Za-z0-9_]‘。
\W 匹配任何非單詞字符。等價於 ‘[^A-Za-z0-9_]‘。

re.match與re.search的區別

re.match只匹配字符串的開始,如果字符串開始不符合正則表達式,則匹配失敗,函數返回None;而re.search匹配整個字符串,直到找到一個匹配。

Regular Expression Modifiers: Option Flags

Regular expression literals may include an optional modifier to control various aspects of matching. The modifiers are specified as an optional flag. You can provide multiple modifiers using exclusive OR (|), as shown previously and may be represented by one of these ?

ModifierDescription
re.I Performs case-insensitive matching.
re.L Interprets words according to the current locale. This interpretation affects the alphabetic group (\w and \W), as well as word boundary behavior (\b and \B).
re.M Makes $ match the end of a line (not just the end of the string) and makes ^ match the start of any line (not just the start of the string).
re.S Makes a period (dot) match any character, including a newline.
re.U Interprets letters according to the Unicode character set. This flag affects the behavior of \w, \W, \b, \B.
re.X Permits "cuter" regular expression syntax. It ignores whitespace (except inside a set [] or when escaped by a backslash) and treats unescaped # as a comment marker.

幾個常見正則例子:

匹配手機號

phone_str = "hey my name is alex, and my phone number is 13651054607, please call me if you are pretty!"
phone_str2 = "hey my name is alex, and my phone number is 18651054604, please call me if you are pretty!"
 
m = re.search("(1)([358]\d{9})",phone_str2)
if m:
    print(m.group())

匹配IP V4

ip_addr = "inet 192.168.60.223 netmask 0xffffff00 broadcast 192.168.60.255"
 
m = re.search("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", ip_addr)
 
print(m.group())

分組匹配地址

contactInfo = ‘Oldboy School, Beijing Changping Shahe: 010-8343245‘
match = re.search(r‘(\w+), (\w+): (\S+)‘, contactInfo) #分組
"""
>>> match.group(1)
  ‘Doe‘
  >>> match.group(2)
  ‘John‘
  >>> match.group(3)
  ‘555-1212‘
"""
match = re.search(r‘(?P<last>\w+), (?P<first>\w+): (?P<phone>\S+)‘, contactInfo)
"""
 >>> match.group(‘last‘)
  ‘Doe‘
  >>> match.group(‘first‘)
  ‘John‘
  >>> match.group(‘phone‘)
  ‘555-1212‘
"""

匹配email

email = "[email protected]   http://www.oldboyedu.com"
 
m = re.search(r"[0-9.a-z]{0,26}@[0-9.a-z]{0,20}.[0-9a-z]{0,8}", email)
print(m.group())

python3--正則表達式