正則表達式
\d匹配一個數字
\w匹配一個字母或數字
\s匹配一個空格(包括tab等空白符)
\s+匹配至少一個空格
.匹配任意字符
*匹配任意個字符(包括0個)
+匹配至少一個字符
?匹配0個或者1個字符
{n}匹配n個字符
{n,m}匹配n-m個字符
A|B可以匹配A或B,所以(P|p)ython可以匹配'Python'或者'python'。
^表示行的開頭, ^\d表示必須以數字開頭
$表示行的結束,\d$表示必須以數字結束
^py$整行只能匹配py
[0-9a-zA-Z_]可以匹配一個數字、字母或者下劃線
[0-9a-zA-Z_]+
[a-zA-Z_][0-9a-zA-Z_]*
[a-zA-Z_][0-9a-zA-Z_]{0, 19}
re模塊
- match()方法判斷是否匹配,成功返回Match對象,失敗返回None
re.match(pattern, string, flags)
第一個參數為正則表達式
第二個參數為要匹配的字符串
第三個參數為標志位,匹配方式(是否區分大小寫,多行匹配等)
import re
re.match(r'^\d{3}-\d{3,8}$', '010-12345')
<_sre.SRE_Match object; span=(0, 9), match='010-12345'>
- split()正則表達式切分字符串
re.split(r'\s+', 'a b c')
['a', 'b', 'c']
re.split(r'[\s,]+', 'a,b, c d')
['a', 'b', 'c', 'd']
re.split(r'[\s,;]+', 'a,b;; c d')
['a', 'b', 'c', 'd']
- group()分組提取
m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
m.group(0)
'010-12345'
m.group(1)
'010'
m.group(2)
'12345'
t = '19:05:30'
m = re.match( r'^(0[0-9]|1[0-9]|2[0-3]|[0-9]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9]):(0[0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]|[0-9])$', t)
print(m)
print(m.groups())
<_sre.SRE_Match object; span=(0, 8), match='19:05:30'>
('19', '05', '30')
- 正則表達式默認貪婪匹配
貪婪匹配
re.match(r'^(\d+)(0*)$', '102300').groups()
('102300', '')
非貪婪匹配(盡可能少匹配)加?
re.match(r'^(\d+==?==)(0*)$', '102300').groups()
('1023', '00')
- compile()預編譯,把正則表達式編譯成一個正則表達式對象
import re
# 編譯:
re_telephone = re.compile(r'^(\d{3})-(\d{3,8})$')
# 使用
re_telephone.match('010-12345').groups()
('010', '12345')
re_telephone.match('010-8086').groups()
('010', '8086')
- findall()獲取字符串中所有匹配的字符串
獲取字符串中包含'oo'的所有單詞
re.findall(r'\woo\w', text)
- sub()
re.sub(pattern, repl, string, count)
第二個函數是替換后的字符串,本例為’-‘
第四個函數指替換個數,默認為0,表示每個匹配項都替換
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s+', '-', text)
將字符串中的空格替換成‘[]’
re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0)
- search()
re.search(pattern, string, flags)
匹配直到找到第一個匹配然后返回,如果字符串沒有匹配,則返回None