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')