Python之正則表達式

正則表達式元字符如下:. ^ $ * + ? { } [ ] \ | ( )
 . 匹配除換行符以外的所以字符
 ^ 規定匹配模式必須出現在目標字符串的開頭,例如:^hell    hello    hellboy
$ 規定匹配模式必須出現在目標字符串的結尾,例如:ar$   car   bar
* 其前一個字符必須在目標對象中連續出現零次或多次
 + 其前一個字符必須在目標對象中連續出現一次或多次
? 其前一個字符必須在目標對象中連續出現一次或零次
{n} 匹配確定的n次,例如:o{2} oo
{n,} 至少匹配n次,例如:o{2} oo ooo oooo
{n,m} 至少匹配n次,至多匹配m次,例如:o{2,3} oo ooo
[A-Z] A-Z內任意一個大寫字母
[a-z] a-z內任意一個小寫字母
[0-9] 0-9內任意一個數字,等價於 \d
[A-Za-z0-9] 任意一個字母或數字,等價於 \w
\ 轉義字符,例如[ ==> [ , \==>\
| 管道符號,A和B是任意的RE,那麼A|B就是匹配A或者B的一個新的RE。


\s 用於匹配單個空格,包括tab鍵和換行符
\S 用於匹配單個空格之外的所有字符
\d 匹配0-9的數字
\w 匹配字母、數字或下劃線
\W 匹配所有和\w不匹配的字符


使用正則表達式
re.compile(pattern, flags=0)
編譯正則表達式,返回一個 pattern 對象。

>>>prog = re.compile(pattern)
>>>result = prog.match(string)

等價於

>>>result = re.match(pattern, string)

第一種方式能實現正則表達式的重用。

re.match(pattern, string, flags=0)
如果字符串的開頭能匹配正則表達式,返回對應的 match 對象,否則返回None。

re.search(pattern, string, flags=0)
在字符串中查找,是否能匹配正則表達式,若是,返回對應的 match 對象,否則返回None。

re.split(pattern, string, maxsplit=0, flags=0)
使用正則表達式分離字符串。如果用括號將正則表達式括起來,那麼匹配的字符串也會被列入到list中返回。maxsplit是分離的次數,maxsplit=1分離一次,默認爲0,不限制次數。

>>> p = re.compile(r'\W+')
>>> p2 = re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '']
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

re.findall(pattern, string, flags=0)
找到 RE 匹配的所有子串,並把它們作爲一個列表返回。如果無匹配,返回空列表。

>>> p = re.compile('\d+')
>>> p.findall('12 drummers drumming, 11 pipers piping, 10 lords a-leaping')
['12', '11', '10']

re.finditer(pattern, string, flags=0)
找到 RE 匹配的所有子串,並把它們作爲一個迭代器返回。

>>> p = re.compile('\d+')
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator  
<callable_iterator object at 0x...>
>>> for match in iterator:
...     print(match.span())
...
(0, 2)
(22, 24)
(29, 31)

re.sub(pattern, repl, string, count=0, flags=0)
找到 RE 匹配的所有子串,並將其用一個不同的字符串替換。可選參數 count 是模式匹配後替換的最大次數;count 必須是非負整數。缺省值是 0 表示替換所有的匹配。如果無匹配,字符串將會無改變地返回。

group([group1, …])

>>> m = re.match(r"(\w+) (\w+)", "Isaac Newton, physicist")
>>> m.group(0)       # 整個匹配
'Isaac Newton'
>>> m.group(1)       # 第一個子串
'Isaac'
>>> m.group(2)       # 第二個子串
'Newton'
>>> m.group(1, 2)    # 多個子串組成的元組
('Isaac', 'Newton')

如果有其中有用(?P…)這種語法命名過的子串的話,相應的groupN也可以是名字字符串。例如:

>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
>>> m.group('first_name')
'Malcolm'
>>> m.group('last_name')
'Reynolds'

groups(default=None)
返回一個由所有匹配到的子串組成的元組。

>>> m = re.match(r"(\d+)\.(\d+)", "24.1632")
>>> m.groups()
('24', '1632')

default的作用:

>>> m = re.match(r"(\d+)\.?(\d+)?", "24")
>>> m.groups()      # 第二個默認是None
('24', None)
>>> m.groups('0')   # 現在默認是0了
('24', '0')


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