1. re基礎(chǔ)
1.1 正則在不同的語言中有區(qū)別,但是大部分是通用的

re元字符和語法
1.2 貪婪和非貪婪(默認(rèn)是貪婪的)
開啟非貪婪模式需要在表達(dá)式后加"?"
1.3 轉(zhuǎn)移字符 ""
原生字符串r"\d"解決了匹配"\d"的問題
1.4 匹配模式
re.compile(pattern[,flag])
2. re模塊
2.1 用法
import re
pattern = re.compile(r"hello")
match = pattern.match("hello world.")
if match:
print(match.group())
- re.compile(str,flag)
負(fù)責(zé)將字符串形式的正則表達(dá)式編譯成pattern對象
匹配模式有:- re.I,忽略大小寫
- re.M 多行模式
- re.S 任意匹配模式
a = re.compile(r"""\d+ #intergal part
\. #decimal part
\d* #fractional digits""",re.X)
#等價于
b = re.compile(r"\d+\.\d*")
m = re.match(r"hello","hello world.")
print(m.group())
2.2 match
match對象是一次匹配的結(jié)果
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(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'\2 \1\3'):", m.expand(r'\2 \1\3')
2.3 pattern
pattern對象是編譯好的正則表達(dá)式,通過re.compile()構(gòu)造實例
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
#search
import re
# 將正則表達(dá)式編譯成Pattern對象
pattern = re.compile(r'world')
# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None
# 這個例子中使用match()無法成功匹配
match = pattern.search('hello world!')
if match:
# 使用Match獲得分組信息
print match.group()
#split
p = re.compile(r'\d+')
print p.split('one1two2three3four4')
#findall
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')
#sub
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)
- 字符串匹配
re.search("abc","hello abc")
re.search("gray|grey","gray")
re.search("gr(a|e)y","gray")
# 數(shù)量限定
‘+’ 加號代表前面的字符必須至少出現(xiàn)一次
? 問號代表前面的字符最多只可以出現(xiàn)一次
‘*’ 星號代表前面的字符可以不出現(xiàn),也可以出現(xiàn)一次或者多次
[...] 括號里面包含的任意字符
匹配 [0-9],[0-9a-z]
多字符匹配 {n}
[0-9]{3} : []以內(nèi)的字母、數(shù)字在后面字符串中出現(xiàn)的次數(shù)
[]{m,n}, 按照[]內(nèi)規(guī)則匹配 m---n之間個數(shù),m必須小于n
"." 匹配任何1個字符
"^" 匹配字符串的開始
"$" 匹配字符串的結(jié)尾
'\d' 匹配數(shù)字
'\D' 匹配非數(shù)字
'\w' 匹配任意數(shù)字和字母
'\W' 非數(shù)字和字母
'\s' 匹配任意空白字符,相當(dāng)于 [ \t\n\r\f\v]
\S 匹配任意非空白字符
match() 函數(shù)只在字符串的開始位置嘗試匹配正則表達(dá)式,也就是只報告從位置 0 開始的匹配情況
search() 函數(shù)是掃描整個字符串來查找匹配
split() 將字符串按照規(guī)則分成list
findall() 函數(shù)搜索整個字符串,返回所有匹配項的list
sub() 函數(shù) 查找并替換