正則表達式基礎
Python支持的正則表達式元字符和語法:
語法
語法 | 說明 | 表達式實例 | 完整匹配的字符串 |
---|---|---|---|
字符 | |||
一般字符 | 匹配自身 | abc | abc |
. | 匹配除換行符”\n”之外的任意字符 | a.c | abc |
\ | 轉義字符,使後一個字符改變原來的意思 | a\\c | a\c |
[…] | 1、字符集。對應的位置可以是字符集中的任意字符。 | a[bcd]e | abe |
2、字符集中的字符可以逐個列出,也可以給出範圍,如[abc]或[a-c]。 | ace | ||
3、第一個字符如果是^表示取反,如[^abc]表示不是abc的其他字符。 | ade | ||
4、所有特殊字符在字符集中都失去原有的特殊含義 | |||
5、在字符集中如果使用]、-、^時,可以在前面加上反斜槓 | |||
或把 ]、-放在第一個字符,把^放在非第一個字符 | |||
預定義字符集(可寫在字符集[…]中) | |||
\d | 數字:[0-9] | a\dc | a1c |
\D | 非數字:[^\d] | a\Dc | abc |
\s | 空白字符:[<空格>\t\r\n\f\v] | a\sc | a c |
\S | 非空白字符:[^\s] | a\Sc | abc |
\w | 單詞字符:[A-Za-Z0-9_] | a\wc | a_c |
\W | 非單詞字符:[^\w] | a\Wc | a c |
數量詞(用在字符或(…)之後) | |||
* | 匹配前一個字符0次或無限次 | abc* | ab or abccc |
+ | 匹配前一個字符1次或無限次 | abc+ | abc or abccc |
? | 匹配前一個字符0次或1次 | abc? | ab or abc |
{m} | 匹配前一個字符m次 | a{3}bc | aaabc |
{m,n} | 匹配前一個字符m至n次.省略m即{,n},匹配0到n次,省略n即{m,},匹配m到無限次 | a{1,2}bc | abc or aabc |
*? +? ?? {m,n}? | 使*、+、?、{m,n}變成非貪婪模式 | ||
邊界匹配(不消耗待匹配字符串中的字符) | |||
^ | 匹配字符串的開頭,在多行模式中匹配每一行的開頭 | ^abc | abc |
$ | 匹配字符串的末尾,在多行模式中匹配每一行的末尾 | $abc | abc |
\A | 僅匹配字符串開頭 | \Aabc | abc |
\Z | 僅匹配字符串末尾 | abc\Z | abc |
\b | 匹配\w和\W之間,即單詞字符和非單詞字符之間,例如單詞和空格間的位置 | a\b!bc | a!bc |
\B | [^\b] | a\Bbc | abc |
邏輯、分組 | |||
| | |代表左右表達式任意匹配一個。先嚐試匹配左邊的表達式,成功則跳過匹配。 | abc|def | abc |
如果|沒有被包含在()中,則它的範圍是整個正則表達式 | def | ||
(…) | 1、被括起來的表達式將作爲分組,從表達式左邊開始每遇到一個 | (abc){2} | abcabc |
分組的左括號’(‘,編號+1。 | a(123|456)c | a123c | |
2、分組作爲一個整體,可以後接數量詞。 | |||
3、表達式中的|僅在該分組中有效 | |||
(?P< name>…) | 分組,除了原有的編號外再指定一個額外的別名 | (?P< id>abc){2} | abcabc |
\< number> | 引用編號爲< number>的分組匹配到的字符串 | (\d)abc\1 | 1abc1 or 7abc7 |
(?P=name) | 引用別名爲< name>的分組匹配到的字符串 | (?P< id>\d)abc(?P=id) | 1abc1 or 7abc7 |
特殊構造(不作爲分組) | |||
(?:…) | (…)的不分組版本,用於使用|或後接數量詞 | (?:abc){2} | abcabc |
(?:iLmsux) | iLmsux的每個字符代表一個匹配模式,只能用在正則表達式的開頭 | (?i)abc | AbC |
可選多個 | |||
(?#…) | 後的內容將作爲註釋被忽略 | abc(?#comment)123 | abc123 |
(?=…) | 之後的字符串內容需要匹配表達式才能成功匹配,不消耗字符串內容 | a(?=\d) | 後面是數字的a |
(?!…) | 之後的字符串內容需要不匹配表達式才能成功匹配,不消耗字符串內容 | a(?!\d) | 後面不是數字的a |
(?<=…) | 之前的字符串內容需要匹配表達式才能成功匹配,不消耗字符串內容 | (?<=\d)a | 前面是數字的a |
(? | 之前的字符串內容需要不匹配表達式才能成功匹配,不消耗字符串內容 | (? | 前面不是數字的a |
(?(id/name)yes-pattern|no-pattern) | 如果編號爲id或者別名爲name的分組匹配到字符,則需要匹配yes-pattern, | (\d)abc(?(1)\d|abc) | 1abc2 |
否則需要匹配no-pattern。no-pattern可以省略。 | abcabc |
數量詞的貪婪與非貪婪模式
貪婪模式總是嘗試匹配儘可能多的字符,非貪婪模式總是嘗試匹配盡肯能少的字符,在Python中,數量詞默認是貪婪的。
如:”ab*”用於查找abbbc,將找到abbb,”ab*?”將找到a。
re模塊
python通過re模塊支持正則表達式
使用re一般步驟爲:
1.先將正則表達式的字符串形式編譯爲Pattern實例
2.然後使用Pattern實例處理文本並獲取匹配的結果(一個Match實例)
3.最後使用Match實例獲得信息,進行其他的操作
# -*- coding: utf-8 -*-
#一個簡單的re實例,匹配字符串中的hello字符串
import re #導入re模塊
# 將正則表達式編譯成Pattern對象,注意hello前面的r的意思是“原生字符串”
pattern = re.compile(r'hello')
# 使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回None
match1 = pattern.match('hello world!')
match2 = pattern.match('helloo world!')
match3 = pattern.match('helllo world!')
#如果match1匹配成功
if match1:
# 使用Match獲得分組信息
print match1.group()
else:
print 'match1匹配失敗!'
#如果match2匹配成功
if match2:
# 使用Match獲得分組信息
print match2.group()
else:
print 'match2匹配失敗!'
#如果match3匹配成功
if match3:
# 使用Match獲得分組信息
print match3.group()
else:
print 'match3匹配失敗!'
compile
re.compile(strPattern[, flag]):
這個方法是Pattern類的工廠方法,用於將字符串形式的正則表達式編譯爲Pattern對象。第二個參數flag是匹配模式,取值可以使用按位或運算符’|’表示同時生效,比如re.I | re.M。另外,也可以在regex字符串中指定模式,比如re.compile(‘pattern’, re.I | re.M)與re.compile(‘(?im)pattern’)是等價的。
可選值有:
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): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,並可以加入註釋。
以下兩個正則表達式是等價的:
# -*- coding: utf-8 -*-
#兩個等價的re匹配,匹配一個小數
import re
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
re模塊還提供了一個方法escape(string),用於將string中的正則表達式元字符如*/+/?等之前加上轉義符再返回
Match
Match對象是一次匹配的結果,包含了很多關於此次匹配的信息,可以使用Match提供的可讀屬性或方法來獲取這些信息。
屬性:
1.string: 匹配時使用的文本
2.re: 匹配時使用的Pattern對象。
3.pos: 文本中正則表達式開始搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
4.endpos: 文本中正則表達式結束搜索的索引。值與Pattern.match()和Pattern.seach()方法的同名參數相同。
5.lastindex: 最後一個被捕獲的分組在文本中的索引。如果沒有被捕獲的分組,將爲None。
6.lastgroup: 最後一個被捕獲的分組的別名。如果這個分組沒有別名或者沒有被捕獲的分組,將爲None。
方法:
1.group([group1, …]):獲得一個或多個分組截獲的字符串;指定多個參數時將以元組形式返回。group1可以使用編號也可以使用別名;編號0代表整個匹配的子串;不填寫參數時,返回group(0);沒有截獲字符串的組返回None;截獲了多次的組返回最後一次截獲的子串。
2.groups([default]):以元組形式返回全部分組截獲的字符串。相當於調用group(1,2,…last)。default表示沒有截獲字符串的組以這個值替代,默認爲None。
3.groupdict([default]):返回已有別名的組的別名爲鍵、以該組截獲的子串爲值的字典,沒有別名的組不包含在內。default含義同上。
4.start([group]): 返回指定的組截獲的子串在string中的起始索引(子串第一個字符的索引)。group默認值爲0。
5.end([group]):返回指定的組截獲的子串在string中的結束索引(子串最後一個字符的索引+1)。group默認值爲0。
6.span([group]):返回(start(group), end(group))。
7.expand(template): 將匹配到的分組代入template中然後返回。template中可以使用\id或\g< id>、\g< name>引用分組,但不能使用編號0。\id與\g< id>是等價的;但\10將被認爲是第10個分組,如果你想表達\1之後是字符’0’,只能使用\g<1>0。
# -*- 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<2> \g<1>\g<3>'):", m.expand(r'\2 \1\3')
### output ###
# m.string: hello world!
# m.re: <_sre.SRE_Pattern object at 0x016E1A38>
# 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!
Pattern
Pattern對象是一個編譯好的正則表達式,通過Pattern提供的一系列方法可以對文本進行匹配查找。Pattern不能直接實例化,必須使用re.compile()進行構造,也就是re.compile()返回的對象。Pattern提供了幾個可讀屬性用於獲取表達式的相關信息:
1.pattern: 編譯時用的表達式字符串。
2.flags: 編譯時用的匹配模式。數字形式。
3.groups: 表達式中分組的數量。
4.groupindex: 以表達式中有別名的組的別名爲鍵、以該組對應的編號爲值的字典,沒有別名的組不包含在內。
# -*- coding: utf-8 -*-
#一個簡單的pattern實例
import re
p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)
print "p.pattern:", p.pattern
print "p.flags:", p.flags
print "p.groups:", p.groups
print "p.groupindex:", p.groupindex
### output ###
# p.pattern: (\w+) (\w+)(?P<sign>.*)
# p.flags: 16
# p.groups: 3
# p.groupindex: {'sign': 3}
pattern的實例方法及其使用:
match
match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):
這個方法將從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。
pos和endpos的默認值分別爲0和len(string);
注意:這個方法並不是完全匹配。當pattern結束時若string還有剩餘字符,仍然視爲成功。想要完全匹配,可以在表達式末尾加上邊界匹配符’$’。
# encoding: UTF-8
import re
# 將正則表達式編譯成Pattern對象
pattern = re.compile(r'hello')
# 使用Pattern匹配文本,獲得匹配結果,無法匹配時將返回None
match = pattern.match('hello world!')
if match:
# 使用Match獲得分組信息
print match.group()
### 輸出 ###
# hello
search
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
這個方法用於查找字符串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;若無法匹配,則將pos加1後重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。pos和endpos的默認值分別爲0和len(string))。
和match的區別:
match()函數只檢測re是不是在string的開始位置匹配;
search()會掃描整個string查找匹配。
match()只有在0位置匹配成功的話纔有返回,如果不是開始位置匹配成功的話,match()就返回none
例如:
print(re.match(‘super’, ‘superstition’).span())
會返回(0, 5)
print(re.match(‘super’, ‘insuperable’))
則返回None
search()會掃描整個字符串並返回第一個成功的匹配
例如:
print(re.search(‘super’, ‘superstition’).span())
返回(0, 5)
print(re.search(‘super’, ‘insuperable’).span())
返回(2, 7)
split
split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。
import re
p = re.compile(r'\d+')
print p.split('one1two2three3four4')
### output ###
# ['one', 'two', 'three', 'four', '']
findall
findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。
import re
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')
### output ###
# ['1', '2', '3', '4']
finditer
finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。
import re
p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
print m.group(),
### output ###
# 1 2 3 4
sub
sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替換string中每一個匹配的子串後返回替換後的字符串。
當repl是一個字符串時,可以使用\id或\g< id>、\g< name>引用分組,但不能使用編號0。當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。count用於指定最多替換次數,不指定時全部替換。
import re
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
print p.sub(r'\2 \1', s)
def func(m):
return m.group(1).title() + ' ' + m.group(2).title()
print p.sub(func, s)
### output ###
# say i, world hello!
# I Say, Hello World!
subn
subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替換次數)。
import re
p = re.compile(r'(\w+) (\w+)')
s = 'i say, hello world!'
print p.subn(r'\2 \1', s)
def func(m):
return m.group(1).title() + ' ' + m.group(2).title()
print p.subn(func, s)
### output ###
# ('say i, world hello!', 2)
# ('I Say, Hello World!', 2)