python常用正則表達式規則表
圖片來自CSDN
正則匹配中r含義
r表示raw的簡及raw string 意思是原生字符,也就是說是這個字符串中間的特殊字符不用轉義。比如你要表示‘\n’,可以這樣:r'\n'。但是如果你不用原生字符 而是用字符串你得這樣:‘\\n’
re模塊的使用
使用Python中的re模塊,將正則表達式編譯爲正則對象,提升代碼的執行效率
例子:
import timeit
#將正則表達式賦值給reg變量,後面使用match方法調用該對象
print (timeit.timeit(setup='''import re; reg = re.compile('<(?P<tagname>\w*)>.*</(?P=tagname)>')''', stmt='''reg.match('<h1>xxx</h1>')''', number=1000000))
#每次都要先調用正則表達式
print (timeit.timeit(setup='''import re''', stmt='''re.match('<(?P<tagname>\w*)>.*</(?P=tagname)>', '<h1>xxx</h1>')''', number=1000000))
輸出:
3.2538992546554226
7.934942773753158
re.compile(pattern[, flags])使用
這個方法是就是將字符串的正則表達式編譯爲正則對象,第二個參數flag是匹配模式,取值可以使用按位或者運算符“|”表示同時生效,比如:re.I | re.M,flag的可選值有:
re.I(re.IGNORECASE): 忽略大小寫(括號內是完整寫法,下同)
M(MULTILINE): 多行模式,改變'^'和'$'的行爲
S(DOTALL): 點任意匹配模式,改變'.'的行爲
L(LOCALE): 使預定字符類 \w \W \b \B \s \S 取決於當前區域設定
U(UNICODE): 使預定字符類 \w \W \b \B \s \S \d \D 取決於unicode定義的字符屬性
X(VERBOSE): 詳細模式。這個模式下正則表達式可以是多行,忽略空白字符,並可以加入註釋。以下兩個正則表達式是等價的:
a = re.compile(r"""\d + # the integral part
\. # the decimal point
\d * # some fractional digits""", re.X)
b = re.compile(r"\d+\.\d*")
match方法
match(string[, pos[, endpos]])
string:匹配使用的文本,
pos: 文本中正則表達式開始搜索的索引。及開始搜索string的下標
endpos: 文本中正則表達式結束搜索的索引。
如果不指定pos,默認是從開頭開始匹配,如果匹配不到,直接返回None
例子:
import re
pattern = re.compile(r'\w*(hello w.*)(hellol.*)')
result = pattern.match(r'aahello worldhello ling')
print(result)
result2 = pattern.match(r'hello world helloling')
print(result2.groups())
輸出:
None
('hello world ', 'hello ling')
我們可以看到result1已經由字符串轉換成了一個正則對象。rangeesule.groups()可以查看出來所有匹配到的數據,每個()是一個元素,最終返回一個tuple。group()既可以通過下標(從1開始)的方式訪問,也可以通過分組名進行訪問。groupdict只能顯示有分組名的數據。
例子2:
import re
prog = re.compile(r'(?P<tagname>abc)(.*)(?P=tagname)')
result1 = prog.match('abclfjlad234sjldabc')
print(result1)
print(result1.groups())
print result1.group('tagname')
print(result1.group(2))
print(result1.groupdict())
輸出:
<_sre.SRE_Match object at 0x0000000002176E88>
('abc', 'lfjlad234sjld')
abc
lfjlad234sjld
{'tagname': 'abc'}
search方法
不建議使用search方法,search方法相較match方法效率低下
例子:
import re
pattern = re.compile(r'(hello w.*)(hellol.*)')
result1 = pattern.search(r'aahello worldhello ling')
print(result1.groups())
輸出:
('hello world ', 'hello ling')
spilt方法
split(string[, maxsplit])
按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。
例子:
import re
p = re.compile(r'\d+')
print(p.split('one1two2three3four4'))
輸出:
['one', 'two', 'three', 'four', '']
findall方法
findall(string[, pos[, endpos]])
搜索string,以列表形式返回全部能匹配的子串.
例子:
import re
p = re.compile(r'\d+')
print(findall('one1two2three3four4'))
輸出:
['1', '2', '3', '4']
findditer方法
finditer(string[, pos[, endpos]])
搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。
例子:
import re
p = re.compile(r'\d+')
print(type(p.finditer('one1two2three3four4')))
for m in p.finditer('one1two2three3four4'):
print(type(m))
print(m.group())
輸出:
<type 'callable-iterator'>
<type '_sre.SRE_Match'>
1
<type '_sre.SRE_Match'>
2
<type '_sre.SRE_Match'>
3
<type '_sre.SRE_Match'>
4
sub方法
sub(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))
輸出:
say i, world hello!
I Say, Hello World!