Python正規則表達式

python中主要使用re模塊進行正則操作
圖片描述
這是python正則基本元字符
. 如 r.d 會匹配 red、r d等。不會匹配read;
* 如 r*ed 會匹配 ed、rred、rrrred、red等。;
+ 如 r+ed 會匹配 rred、rrred等。不會匹配ed;
| 如 abc|acd。會匹配abc或者acd;
[] 匹配[]中任一字符 如r[bc]d,匹配rbd或者rcd;
貪婪與非貪婪模式可以看一下
^與[Math Processing Error]只會匹配第三行的
如果嫌轉義符麻煩可以使用r 如re.match(r’hello’,str)

元字符可以結合使用
.*匹配任意個字符 r.*d可以匹配rd red read等
.+匹配一個或多個 r.+d匹配 red read等
.?匹配0個或一個

例子匹配號碼
如13134567890
13[0-9][0-9]{8}或者13[0-9]{9}

匹配網址
http://www|www).[a-zA-Z0-9]*.{a-z}{2,3}
or r’(http://www|www).[a-zA-Z0-9]*.{a-z}{2,3}’

主要使用函數 re.match()
re.findall()
re.search()
re.sub()
re.subn()
re.spilt()

match與search差不多match是從str第一個開始匹配 search則是搜索整個str
例如 s=’hello world ichunqiu’
re.match(‘world’,s)與·re.search(‘world’,s)結果不一樣
re.match(‘WORLD’,s,re.I)可以忽略大小寫(re.I)

re.sub()與re.subn()區別
re.sub(‘world’,’beauty’,s)
‘hello beauty ichunqiu’

re.subn(‘hello’,’beauty’,s)
(‘beauty beauty ichunqiu’,1(替換次數))

相關鏈接:http://bbs.ichunqiu.com/thread-9082-1-1.html?from=csdnJG