Python 的 re 子產品(Regular Expression 正規表達式)提供各種正規表達式的比對操作,在文本解析、複雜字元串分析和資訊提取時是一個非常有用的工具,下面我主要總結了re的常用方法。
1.re的簡介
使用python的re子產品,盡管不能滿足所有複雜的比對情況,但足夠在絕大多數情況下能夠有效地實作對複雜字元串的分析并提取出相關資訊。python 會将正規表達式轉化為位元組碼,利用 C 語言的比對引擎進行深度優先的比對。
- import re
- print re.__doc__
可以查詢re子產品的功能資訊,下面會結合幾個例子說明。
文法 | 意義 | 說明 |
---|---|---|
"." | 任意字元 | |
"^" | 字元串開始 | '^hello'比對'helloworld'而不比對'aaaahellobbb' |
"$" | 字元串結尾 | 與上同理 |
"*" | 0 個或多個字元(貪婪比對) | <*>比對<title>chinaunix</title> |
"+" | 1 個或多個字元(貪婪比對) | 與上同理 |
"?" | 0 個或多個字元(貪婪比對) | 與上同理 |
*?,+?,?? | 以上三個取第一個比對結果(非貪婪比對) | <*>比對<title> |
{m,n} | 對于前一個字元重複m到n次,{m}亦可 | a{6}比對6個a、a{2,4}比對2到4個a |
{m,n}? | 對于前一個字元重複m到n次,并取盡可能少 | ‘aaaaaa’中a{2,4}隻會比對2個 |
"\\" | 特殊字元轉義或者特殊序列 | |
[] | 表示一個字元集 | [0-9]、[a-z]、[A-Z]、[^0] |
"|" | 或 | A|B,或運算 |
(...) | 比對括号中任意表達式 | |
(?#...) | 注釋,可忽略 | |
(?=...) | Matches if ... matches next, but doesn't consume the string. | '(?=test)' 在hellotest中比對hello |
(?!...) | Matches if ... doesn't match next. | '(?!=test)' 若hello後面不為test,比對hello |
(?<=...) | Matches if preceded by ... (must be fixed length). | '(?<=hello)test' 在hellotest中比對test |
(?<!...) | Matches if not preceded by ... (must be fixed length). | '(?<!hello)test' 在hellotest中不比對test |
正規表達式特殊序清單如下:
特殊序列符号 | 意義 |
---|---|
\A | 隻在字元串開始進行比對 |
\Z | 隻在字元串結尾進行比對 |
\b | 比對位于開始或結尾的空字元串 |
\B | 比對不位于開始或結尾的空字元串 |
\d | 相當于[0-9] |
\D | 相當于[^0-9] |
\s | 比對任意空白字元:[\t\n\r\r\v] |
\S | 比對任意非空白字元:[^\t\n\r\r\v] |
\w | 比對任意數字和字母:[a-zA-Z0-9] |
\W | 比對任意非數字和字母:[^a-zA-Z0-9] |
3.re的主要功能函數
1、compile()
編譯正規表達式模式,傳回一個對象的模式。(可以把那些常用的正規表達式編譯成正規表達式對象,這樣可以提高一點效率。)
格式:
re.compile(pattern,flags=0)
pattern: 編譯時用的表達式字元串。
flags 編譯标志位,用于修改正規表達式的比對方式,如:是否區分大小寫,多行比對等。常用的flags有:
标志 | 含義 |
---|---|
re.S(DOTALL) | 使.比對包括換行在内的所有字元 |
re.I(IGNORECASE) | 使比對對大小寫不敏感 |
re.L(LOCALE) | 做本地化識别(locale-aware)比對,法語等 |
re.M(MULTILINE) | 多行比對,影響^和$ |
re.X(VERBOSE) | 該标志通過給予更靈活的格式以便将正規表達式寫得更易于了解 |
re.U | 根據Unicode字元集解析字元,這個标志影響\w,\W,\b,\B |
import re
tt = "Tina is a good girl, she is cool, clever, and so on..."rr = re.compile(r'\w*oo\w*')print(rr.findall(tt)) #查找所有包含'oo'的單詞執行結果如下:
['good', 'cool']
複制
2、match()
決定RE是否在字元串剛開始的位置比對。//注:這個方法并不是完全比對。當pattern結束時若string還有剩餘字元,仍然視為成功。想要完全比對,可以在表達式末尾加上邊界比對符'$'
格式:
re.match(pattern, string, flags=0)
print(re.match('com','comwww.runcomoob').group())print(re.match('com','Comwww.runcomoob',re.I).group())
執行結果如下:
com
com
複制
3、search()
格式:
re.search(pattern, string, flags=0)
re.search函數會在字元串内查找模式比對,隻要找到第一個比對然後傳回,如果字元串沒有比對,則傳回None。
print(re.search('\dcom','www.4comrunoob.5com').group())
執行結果如下:
4com
複制
*注:match和search一旦比對成功,就是一個match object對象,而match object對象有以下方法:
- group() 傳回被 RE 比對的字元串
- start() 傳回比對開始的位置
- end() 傳回比對結束的位置
- span() 傳回一個元組包含比對 (開始,結束) 的位置
- group() 傳回re整體比對的字元串,可以一次輸入多個組号,對應組号比對的字元串。
a. group()傳回re整體比對的字元串,
b. group (n,m) 傳回組号為n,m所比對的字元串,如果組号不存在,則傳回indexError異常
c.groups()groups() 方法傳回一個包含正規表達式中所有小組字元串的元組,從 1 到所含的小組号,通常groups()不需要參數,傳回一個元組,元組中的元就是正規表達式中定義的組。
=
(re.search(,a).group(0))
(re.search(,a).group(1))
(re.search(,a).group(2))
(re.search(,a).group(3))
複制
4、findall()
re.findall周遊比對,可以擷取字元串中所有比對的字元串,傳回一個清單。
格式:
re.findall(pattern, string, flags=0)
p = re.compile(r'\d+')print(p.findall('o1n2m3k4'))
執行結果如下:
['1', '2', '3', '4']
複制
import re
tt = "Tina is a good girl, she is cool, clever, and so on..."rr = re.compile(r'\w*oo\w*')print(rr.findall(tt))print(re.findall(r'(\w)*oo(\w)',tt))#()表示子表達式 執行結果如下:
['good', 'cool']
[('g', 'd'), ('c', 'l')]
複制
5、finditer()
搜尋string,傳回一個順序通路每一個比對結果(Match對象)的疊代器。找到 RE 比對的所有子串,并把它們作為一個疊代器傳回。
格式:
re.finditer(pattern, string, flags=0)
iter = re.finditer(r'\d+','12 drumm44ers drumming, 11 ... 10 ...')for i in iter: print(i) print(i.group()) print(i.span())
執行結果如下:<_sre.SRE_Match object; span=(0, 2), match='12'>
12(0, 2)<_sre.SRE_Match object; span=(8, 10), match='44'>
44(8, 10)<_sre.SRE_Match object; span=(24, 26), match='11'>
11(24, 26)<_sre.SRE_Match object; span=(31, 33), match='10'>
10(31, 33)
複制
6、split()
按照能夠比對的子串将string分割後傳回清單。
可以使用re.split來分割字元串,如:re.split(r'\s+', text);将字元串按空格分割成一個單詞清單。
格式:
re.split(pattern, string[, maxsplit])
maxsplit用于指定最大分割次數,不指定将全部分割。
print(re.split('\d+','one1two2three3four4five5'))
執行結果如下:
['one', 'two', 'three', 'four', 'five', '']
複制
7、sub()
使用re替換string中每一個比對的子串後傳回替換後的字元串。
格式:
re.sub(pattern, repl, string, count)
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."print(re.sub(r'\s+', '-', text))
執行結果如下:
JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...
複制
其中第二個函數是替換後的字元串;本例中為'-'
第四個參數指替換個數。預設為0,表示每個比對項都替換。
re.sub還允許使用函數對比對項的替換進行複雜的處理。
如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字元串中的空格' '替換為'[ ]'。
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."print(re.sub(r'\s+', lambda m:'['+m.group(0)+']', text,0))
執行結果如下:
JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...
複制
8、subn()
傳回替換次數
格式:
subn(pattern, repl, string, count=0, flags=0)
print(re.subn('[1-2]','A','123456abcdef'))print(re.sub("g.t","have",'I get A, I got B ,I gut C'))print(re.subn("g.t","have",'I get A, I got B ,I gut C'))
執行結果如下:
('AA3456abcdef', 2)
I have A, I have B ,I have C
('I have A, I have B ,I have C', 3)
複制