1. 程式人生 > 程式設計 >學會Python正則表示式,就看這20個例子(指令碼之家修正版)

學會Python正則表示式,就看這20個例子(指令碼之家修正版)

正則表示式是處理字串的強大工具。作為一個概念而言,正則表示式對於Python來說並不是獨有的。但是,Python中的正則表示式在實際使用過程中還是有一些細小的差別。

正則表示式是一個特殊的字元序列,它能幫助你方便的檢查一個字串是否與某種模式匹配。

Python 自1.5版本起增加了re 模組,它提供 Perl 風格的正則表示式模式。

re 模組使 Python 語言擁有全部的正則表示式功能。

compile 函式根據一個模式字串和可選的標誌引數生成一個正則表示式物件。該物件擁有一系列方法用於正則表示式匹配和替換。

re 模組也提供了與這些方法功能完全一致的函式,這些函式使用一個模式字串做為它們的第一個引數。

1、查詢第一個匹配串

import re
s='ilovepythonverymuch'
pat='python'
r=re.search(pat,s)
print(r.span())#(7,13)

2、查詢所有1

import re
s='山東省濰坊市青州第1中學高三1班'
pat='1'
r=re.finditer(pat,s)
for i in r:
 print(i)
 
#<re.Matchobject;span=(9,10),match='1'>
#<re.Matchobject;span=(14,15),match='1'>

3、\d匹配數字[0-9]

import re
s='一共20行程式碼執行時間13.59s'
pat=r'\d+'#+表示匹配數字(\d表示數字的通用字元)1次或多次
r=re.findall(pat,s)
print(r)
#['20','13','59']

我們想保留13.59而不是分開,請看4

4、?表示前一個字元匹配0或1次

import re

s='一共20行程式碼執行時間13.59s'
pat=r'\d+\.?\d+'#?表示匹配小數點(\.)0次或1次
r=re.findall(pat,'13.59']

5、^匹配字串的開頭

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'^[emrt]' #查詢以
r=re.findall(pat,s)
print(r)
#[],因為字串的開頭是字元`T`,不在emrt匹配範圍內,所以返回為空

6、re.I 忽略大小寫

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'^[emrt]' #查詢以
r=re.compile(pat,re.I).search(s)
print(r)
#<re.Matchobject;span=(0,1),match='T'>表明字串的開頭在匹配列表中

7、使用正則提取單詞

這是不準確版本,請參看第9個

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'\s[a-zA-Z]+'
r=re.findall(pat,s)
print(r) #['module','provides','regular','expression','matching','operations','similar','to','those','found','in','Perl']

8、只捕獲單詞,去掉空格

使用()捕獲,這是不準確版本,請參看第9個

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'\s([a-zA-Z]+)'
r=re.findall(pat,s)
print(r)
#['module','Perl']

9、補充上第一個單詞

上面第8,看到提取單詞中未包括第一個單詞,使用?表示前面字元出現0次或1次,但是此字元還有表示貪心或非貪心匹配含義,使用時要謹慎。

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'\s?([a-zA-Z]+)'
r=re.findall(pat,s)
print(r)
#['This','module','Perl']

10、使用split函式直接分割單詞

使用以上方法分割單詞,不是簡潔的,僅僅為了演示。分割單詞最簡單還是使用split函式。

import re

s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s+'
r = re.split(pat,'Perl']

11、提取以m或t開頭的單詞,忽略大小寫

下面出現的結果不是我們想要的,原因出在 ?上!

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'\s?([mt][a-zA-Z]*)' # 查詢以
r=re.findall(pat,'tions','milar','those']

12、使用^查詢字串開頭的單詞

綜合11和12得到所有以m或t開頭的單詞

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'^([mt][a-zA-Z]*)\s' # 查詢以
r=re.compile(pat,re.I).findall(s)
print(r) 
#['This']

13、先分割,再查詢滿足要求的單詞

使用match表示是否匹配

import re

s='ThismoduleprovidesregularexpressionmatchingoperationssimilartothosefoundinPerl'
pat=r'\s+'
r=re.split(pat,s)
res=[i for i in r if re.match(r'[mMtT]',i)]
print(res)
#['This','those']

14、貪心匹配

儘可能多的匹配字元

import re

content='<h>ddedadsad</h><div>graph</div>bb<div>math</div>cc'
pat=re.compile(r"<div>(.*)</div>") #貪婪模式
m=pat.findall(content)
print(m)
#['graph</div>bb<div>math']

15、非貪心匹配

與14相比,僅僅多了一個問號(?),得到結果完全不同。

import re

content='<h>ddedadsad</h><div>graph</div>bb<div>math</div>cc'
pat=re.compile(r"<div>(.*?)</div>") #貪婪模式
m=pat.findall(content)
print(m)
#['graph','math']

與14比較可知,貪心匹配和非貪心匹配的區別,後者是字串匹配後立即返回,見好就收。

16、含有多種分割符

使用split函式

import re

content = 'graph math,english;chemistry' #這種
pat=re.compile(r"[\s\,\;]+") #貪婪模式
m=pat.split(content)
print(m)
#['graph','math','english','chemistry']

17、替換匹配的子串

sub函式實現對匹配子串的替換

import re

content="hello 12345,hello 456321" 
pat=re.compile(r'\d+') #要替換的部分
m=pat.sub("666",content)
print(m)
#hello 666,hello 666

18、爬取百度首頁標題

import re
from urllib import request
 
#爬蟲爬取百度首頁內容
data=request.urlopen("http://www.baidu.com/").read().decode()
 
#分析網頁,確定正則表示式
pat=r'<title>(.*?)</title>'
result=re.search(pat,data)
print(result)
#<re.Match object; span=(1389,1413),match='<title>百度一下,你就知道</title>'>

下面是知識點分享

19、常用元字元總結

.匹配任意字元
^匹配字串始位置
$匹配字串中結束的位置
*前面的原子重複0次1次多次
?前面的原子重複一次或者0次
+前面的原子重複一次或多次
{n}前面的原子出現了n次
{n,}前面的原子至少出現n次
{n,m}前面的原子出現次數介於n-m之間
()分組,需要輸出的部分

20、常用通用字元總結

\s 匹配空白字元
\w 匹配任意字母/數字/下劃線
\W 和小寫 w 相反,匹配任意字母/數字/下劃線以外的字元
\d 匹配十進位制數字
\D 匹配除了十進位制數以外的值
[0-9] 匹配一個0-9之間的數字
[a-z] 匹配小寫英文字母
[A-Z] 匹配大寫英文字母

以上就是Python中正則模組的基本使用總結,裡面有循序漸進的優化分析過程,這些雖然是中間過程,但是對於正則小白而言,瞭解這些很有必要。筆者對於正則的理解也比較膚淺,如有總結不到位之處,懇請指正。