Python 正則表達式

1、正則表達式

正則表達式是對字符串操作的一種邏輯公式,就是用事先定義好的一些特定字符、及這些特定字符的組合,組成一個“規則字符串”,這個“規則字符串”用來表達對字符串的一種過濾邏輯。
正則表達式也是是用來匹配字符串非常強大的工具

正則表達式的大致匹配過程是:
1.依次拿出表達式和文本中的字符比較,
2.如果每一個字符都能匹配,則匹配成功;一旦有匹配不成功的字符則匹配失敗。
3.如果表達式中有量詞或邊界,這個過程會稍微有一些不同。

2、正則表達式語法規則

在這裏插入圖片描述

3、正則表達式相關注解

(1)數量詞的貪婪模式與非貪婪模式
正則表達式通常用於在文本中查找匹配的字符串。Python裏數量詞默認是貪婪的(在少數語言裏也可能是默認非貪婪),總是嘗試匹配儘可能多的字符;非貪婪的則相反,總是嘗試匹配儘可能少的字符。例如:正則表達式”ab*”如果用於查找”abbbc”,將找到”abbb”。而如果使用非貪婪的數量詞”ab*?”,將找到”a”。(我們一般使用非貪婪模式來提取)

(2)反斜槓問題
與大多數編程語言相同,正則表達式裏使用”\”作爲轉義字符,這就可能造成反斜槓困擾。假如你需要匹配文本中的字符”\”,那麼使用編程語言表示的正則表達式裏將需要4個反斜槓”\\”:前兩個和後兩個分別用於在編程語言裏轉義成反斜槓,轉換成兩個反斜槓後再在正則表達式裏轉義成一個反斜槓。

Python裏的原生字符串很好地解決了這個問題,這個例子中的正則表達式可以使用r”\”表示。同樣,匹配一個數字的”\d”可以寫成r”\d”。

4、Python Re模塊

re模塊有如下方法:

#返回pattern對象
re.compile(string[,flag])  
#以下爲匹配所用函數
re.match(pattern, string[, flags])
re.search(pattern, string[, flags])
re.split(pattern, string[, maxsplit])
re.findall(pattern, string[, flags])
re.finditer(pattern, string[, flags])
re.sub(pattern, repl, string[, count])
re.subn(pattern, repl, string[, count])

首先來介紹一下pattern的概念,pattern可以理解爲一個匹配模式,我們需要利用re.compile方法就可以獲得。如下:

pattern=re.complie(r'hello')    r表示原生字符串

其中參數flag是匹配模式,取值可以使用按位或運算符’|’表示同時生效,比如re.I | re.M。
有如下幾種:

 • re.I(全拼:IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
 • re.M(全拼:MULTILINE): 多行模式,改變'^'和'$'的行爲(參見上圖)
 • re.S(全拼:DOTALL): 點任意匹配模式,改變'.'的行爲
 • re.L(全拼:LOCALE): 使預定字符類 \w \W \b \B \s \S 取決於當前區域設定
 • re.U(全拼:UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決於unicode
                        定義的字符屬性
 • re.X(全拼:VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,
                        忽略空白字符,並可以加入註釋。

下面分別來介紹re模塊下的方法:

(1)re.match(pattern, string[, flags])
# !/usr/bin/python

import re

pattern=re.compile(r'hello')

response1=re.match(pattern,'hello')
response2=re.match(pattern,'helo')
if response1:
    print(response1.group())
else:
    print('1匹配失敗')
if response2:
    print(response2.group())
else:
    print('2匹配失敗')

輸出結果:


hello
2匹配失敗

Process finished with exit code 0

關於match對象的的屬性和方法Match對象是一次匹配的結果,包含了很多關於此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。

屬性 作用
string 匹配時使用的文本
re 匹配時使用的Pattern對象
pos 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同
endpos 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
lastindex 最後一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將爲None。
lastgroup 最後一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將爲None。

方法 作用
group([group1, …]) 獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最後一次截獲的子串。
groups([default]) 以元組形式返回全部分組截獲的字符串。相當於調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認爲None。
groupdict([default]) 返回以有別名的組的別名爲鍵、以該組截獲的子串爲值的字典,沒有別名的組不包含在內。default含義同上。
start([group]) 返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值爲0。
end([group]) 返回指定的組截獲的子串在string中的結束索引(子串最後一個字符的索引+1)。group默認值爲0。
span([group]) 返回(start(group), end(group))。
expand(template) 將匹配到的分組代入template中然後返回。template中可以使用\id或\g、\g引用分組,但不能使用編號0。\id與\g是等價的;但\10將被認爲是第10個分組,如果你想表達\1之後是字符’0’,只能使用\g0。

如下代碼:

# -*- coding: utf-8 -*-
#一個簡單的match實例
 
import re
# 匹配如下內容:單詞+空格+單詞+任意字符
m = re.match(r'(\w+) (\w+)(?P<sign>.*)', 'hello world!')
 
print ("m.string:", m.string)
print ("m.re:", m.re)
print ("m.pos:", m.pos)
print ("m.endpos:", m.endpos)
print ("m.lastindex:", m.lastindex)
print ("m.lastgroup:", m.lastgroup)
print ("m.group():", m.group())
print ("m.group(1,2):", m.group(1, 2))
print ("m.groups():", m.groups())
print ("m.groupdict():", m.groupdict())
print ("m.start(2):", m.start(2))
print ("m.end(2):", m.end(2))
print ("m.span(2):", m.span(2))
print (r"m.expand(r'\g \g\g'):", m.expand(r'\2 \1\3'))
 
### output ###
# m.string: hello world!
# m.re: 
# m.pos: 0
# m.endpos: 12
# m.lastindex: 3
# m.lastgroup: sign
# m.group(1,2): ('hello', 'world')
# m.groups(): ('hello', 'world', '!')
# m.groupdict(): {'sign': '!'}
# m.start(2): 6
# m.end(2): 11
# m.span(2): (6, 11)
# m.expand(r'\2 \1\3'): world hello!
(2)re.search(pattern, string[, flags])

search方法與match方法極其類似,區別在於match()函數只檢測re是不是在string的開始位置匹配,search()會掃描整個string查找匹配,match()只有在0位置匹配成功的話纔有返回,如果不是開始位置匹配成功的話,match()就返回None。同樣,search方法的返回對象同樣match()返回對象的方法和屬性。如下代碼:

import re
pattern = re.compile(r'world')
response1= re.search(pattern, 'hello world!')
response2=re.match(pattern,'hello world')
if response1:
   print(response1.group())
else:
   print('flase')
if response2:
   print(response2.group())
else:
   print('flase')

輸出結果如下:


world
flase

Process finished with exit code 0
(3)re.split(pattern, string[, maxsplit])

按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。如下代碼:

import re
 
pattern = re.compile(r'\d+')
print (re.split(pattern,'one1two2three3four4'))
 
### 輸出 ###
# ['one', 'two', 'three', 'four', '']
(4)re.findall(pattern, string[, flags])

搜索string,以列表形式返回全部能匹配的子串。如下代碼:

import re
 
pattern = re.compile(r'\d+')
print (re.findall(pattern,'one1two2three3four4'))
 
### 輸出 ###
# ['1', '2', '3', '4']
(5)re.finditer(pattern, string[, flags])

搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。如下代碼:

import re
 
pattern = re.compile(r'\d+')
for m in re.finditer(pattern,'one1two2three3four4'):
    print (m.group())
 
### 輸出 ###
# 1 2 3 4
(6)re.sub(pattern, repl, string[, count])

使用repl替換string中每一個匹配的子串後返回替換後的字符串。
當repl是一個字符串時,可以使用\id或\g、\g引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。
count用於指定最多替換次數,不指定時全部替換。
如下代碼:

import re
 
pattern = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
 
print re.sub(pattern,r'\2 \1', s)
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print re.sub(pattern,func, s)
 
### output ###
# say i, world hello!
# I Say, Hello World!
(7)re.subn(pattern, repl, string[, count])

返回 (sub(repl, string[, count]), 替換次數)。代碼如下:

import re
 
pattern = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
 
print re.subn(pattern,r'\2 \1', s)
 
def func(m):
    return m.group(1).title() + ' ' + m.group(2).title()
 
print re.subn(pattern,func, s)
 
### output ###
# ('say i, world hello!', 2)
# ('I Say, Hello World!', 2)

合理運用正則表達式對於Python的爬蟲會有很大的用處,而對於爬蟲這方面還要有更深的探究。

發佈了49 篇原創文章 · 獲贊 12 · 訪問量 9766
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章