Python(15)正則表達式

Python正則表達式(Regular Expression)

  • 特殊字符、符號(正則表達式)
  • 正則表達式和Python

特殊字符、符號

. 匹配任何字符
^匹配字符串的開始
$匹配字符串的結尾
*匹配前邊出現的正則表達式0/多次
+匹配前邊出現的正則表達式1/多次
?匹配前邊出現的正則表達式0/1次
{N}匹配前面出現的正則表達式N次
{M,N}
\d匹配任何數字
\w匹配任何數字字母字符
\b匹配任何空白符
\A匹配字符串的起始

Python re模塊函數和方法

compile()

預編譯提升執行性能

match()
從字符串的開頭開始對模式進行匹配,匹配成功,返回一個對象;匹配失敗,返回None

匹配單個

>>> m = re.match('foo','fook')
>>> print m
<_sre.SRE_Match object at 0x000000000248A510>
>>> print m.group()
foo

匹配多個字符串

>>> m = re.match('oo|fo|foo','foo')
>>> print m.group()
fo

匹配任意單個字符

>>> m = re.match('.end','fend')
>>> print m.group()
fend

search()
在一個字符串中查找一個模式

>>> t = re.search('foo', 'ddfoot')
>>> print t.group()
foo

匹配任意單個字符

>>> m = re.search('.end','fds fend')
>>> print m.group()
fend

匹配兩個字符間的字符

>>> m = re.search('f.o','fno')
>>> print m.group()
fno

匹配任意兩個字符

>>> m = re.search('..','fgno')
>>> print m.group()
fg

匹配字符串的開始

>>> print re.search('\Aads','adsthe').group()
ads

匹配任何數字字母字符

>>> print re.search('\w+','af23dsthe').group()
af23dsthe

匹配任何數字

>>> print re.search('\d+','af23dsthe').group()
23

匹配前邊的出現的正則表達式次數2次

>>> print re.search('\d{2}','af234dsthe').group()
23

findall()
沒有找到匹配的部分,會返回空列表;如果陳宮找到匹配的部分,返回所有匹配部分的列表。

>>> m = re.findall('end','fendds fend adsendgg')
>>> print m
['end', 'end', 'end']

split()

>>> m = re.split(':','fendds:fend:adsendgg')
>>> print m
['fendds', 'fend', 'adsendgg']

group()返回全部匹配對象

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章