1 python正則表達(dá)式
python中正則表達(dá)式一般使用自帶的re模塊,本文將簡(jiǎn)單介紹該模塊的使用方法和注意事項(xiàng)。
1.1 原始字符串
在python中使用正則表達(dá)式時(shí),建議使用原始字符串,也就是以r開(kāi)頭的字符串,如r"python"。
1.2 轉(zhuǎn)義字符
在re模塊中有一些特殊字符,如.+?\等,這些字符在正則表達(dá)式中有特殊意義。但是讓我們需要匹配這些符號(hào)時(shí),比如我要匹配字符串中的?號(hào),這時(shí)候就需要使用轉(zhuǎn)義字符了。只需要在這些特殊字符前面加上反斜杠\就可以了。
比如,r"python\.org"用來(lái)匹配python.org
1.3 數(shù)量詞的貪婪模式與非貪婪模式
在使用*+?這這幾個(gè)表示數(shù)量的符號(hào)時(shí),默認(rèn)的情況是貪婪的(盡可能多的匹配字符)。而有時(shí)候需要使用非貪婪模式(盡可能少的匹配字符),這時(shí)候只需要在這幾個(gè)符號(hào)后邊再加一個(gè)?就是非貪婪模式了。例如:
查找字符串"aabbbcc"
貪婪模式下:r"ab*" 將匹配 "aabbb"
非貪婪模式:r"ab*?" 將匹配 "ab"
2 re模塊簡(jiǎn)介
2.1 re模塊方法簡(jiǎn)介
| 方法 | 描述 |
|---|---|
| compile(pattern[, flag]) | 根據(jù)正則表達(dá)式創(chuàng)建匹配對(duì)象 |
| match(pattern, string[, flag]) | 在字符串開(kāi)始處開(kāi)始匹配,返回matchObject或者None |
| search(pattern, string[, flag]) | 在字符串中查找模式,返回matchObject或者None |
| split(pattern, string[, maxsplit]) | 根據(jù)模式的匹配項(xiàng)來(lái)分割字符串 |
| findall(pattern, string[, flag]) | 以列表的形式返回匹配的所有子串 |
| finditer(pattern, string[,flag]) | 返回一個(gè)順序訪問(wèn)每一個(gè)匹配結(jié)果(matchObject)的迭代器 |
| sub(pattern, repl, string[, count]) | 將字符串中的匹配項(xiàng)替換成指定字符串 |
| subn(pattern, repl, string[, count]) | 相比于sub方法,多返回一個(gè)替換次數(shù) |
2.2 re.compile(pattern[, flag])
主要是將一個(gè)正則表達(dá)式編譯成一個(gè)匹配模式對(duì)象(pattern),方便后續(xù)使用 。因?yàn)槭褂谜齽t表達(dá)式匹配字符串時(shí),都需要將正則表達(dá)式編譯成匹配模式對(duì)象(pattern對(duì)象)。對(duì)于要頻繁使用的正則表達(dá)式最好先調(diào)用compile方法將其編譯好,后續(xù)使用時(shí)就省去了編譯的時(shí)間。其中flag參數(shù)主要有如下選項(xiàng):
| flag | 描述 |
|---|---|
| re.I | 忽略大小寫(xiě) |
| re.M | 多行模式 |
| re.S | 點(diǎn)任意匹配模式 |
| re.L | 使預(yù)定義字符類(lèi) \w \W \b \B \s \S 取決于當(dāng)前區(qū)域設(shè)定 |
| re.U | 使預(yù)定義字符類(lèi) \w \W \b \B \s \S 取決于unicode定義的字符屬性 |
| re.X | 詳細(xì)模式,正則表達(dá)式可以是多行的,忽略空白字符,可以加注釋 |
2.3 re.match(pattern[, flag])
從string的開(kāi)頭開(kāi)始匹配,如果成功返回一個(gè)matchObject,否則返回None。matchObject提供如下屬性和方法,來(lái)獲取匹配的子串的信息:
| 方法與屬性 | 描述 |
|---|---|
| string | 匹配時(shí)使用的字符串 |
| re | 匹配時(shí)使用的pattern對(duì)象 |
| pos | 文本中正則表達(dá)式開(kāi)始搜索的索引 |
| endpos | 最后一個(gè)被捕獲的分組在文本中的索引,默認(rèn)為None |
| lastgroup | 最后一個(gè)被捕獲的分組的別名 |
| group([g1, g2, ...]) | 獲得一個(gè)或者多個(gè)分組截獲的字符串;指定多個(gè)參數(shù)時(shí),以元組形式返回;g1可以使用編號(hào)也可以使用別名,其中編號(hào)0表示整個(gè)匹配的子串;默認(rèn)返回None |
| groups() | 以元組的形式返回全部分組截獲的字符串 |
| groupdict() | 返回以有別名的組的別名為鍵、以組截獲的字符串為值的字典,不包含沒(méi)有別名的 |
| start([g]) | 返回指定的組截獲的字串在string中的開(kāi)始索引,group默認(rèn)為0 |
| end([g]) | 返回指定的組截獲的字串在string中的結(jié)束索引(最后一個(gè)字符索引+1),group默認(rèn)為0 |
| span([g]) | 返回(start([group]), end([group])) |
| expand(template) | 將匹配的分組帶入tmplate中返回 |
例程如下:
>>> ptn = re.compile(r"(\w+) (\w+)(?P<sign>.*)")
>>> m = ptn.match("hello world!")
>>> print "m.string:", m.string
m.string: hello world!
>>> print "m.re:", m.re
m.re: <_sre.SRE_Pattern object at 0x10af6c030>
>>> print "m.pos:", m.pos
m.pos: 0
>>> print "m.endpos:", m.endpos
m.endpos: 12
>>> print "m.lastindex:", m.lastindex
m.lastindex: 3
>>> print "m.lastgroup:", m.lastgroup
m.lastgroup: sign
>>> print "m.group():", m.group()
m.group(): hello world!
>>> print "m.group(1,2):", m.group(1, 2)
m.group(1,2): ('hello', 'world')
>>> print "m.groups():", m.groups()
m.groups(): ('hello', 'world', '!')
>>> print "m.groupdict():", m.groupdict()
m.groupdict(): {'sign': '!'}
>>> print "m.start(2):", m.start(2)
m.start(2): 6
>>> print "m.end(2):", m.end(2)
m.end(2): 11
>>> print "m.span(2):", m.span(2)
m.span(2): (6, 11)
>>> print r"m.expand(r'\g \g\g'):", m.expand(r'\2 \1\3')
m.expand(r'\g \g\g'): world hello!
2.4 re.search(pattern[, flag])
掃描整個(gè)string查找匹配的子串,如果成功返回一個(gè)matchObject對(duì)象,否則返回None
2.5 re.split(pattern, string[, maxsplit])
按照能夠匹配的字串將string分割,并返回列表,maxsplit用于指定最大分割次數(shù)。例程如下:
>>> ptn = re.compile(r"\d+")
>>> print ptn.split("one1two2three34four4")
['one', 'two', 'three', 'four', '']
2.6 re.findall(pattern, string[, flag])
搜索string,以列表形式返回全部能夠匹配的子串,例程如下:
>>> ptn = re.compile(r"\d+")
>>> print ptn.findall("one1two2three34four4")
['1', '2', '34', '4']
2.7 re.finditer(pattern, string[, flag])
搜索string,返回一個(gè)順序訪問(wèn)每一個(gè)匹配結(jié)果(MatchObject)的迭代器,例程如下
>>> pattern = re.compile(r'\d+')
>>> for m in re.finditer(pattern,'one1two2three3four4'):
... print m.group()
...
1
2
3
4
2.8 re.sub(pattern, repl, string[, count])
使用repl替換string中每一個(gè)匹配的字串后,返回替換后的字符串
1)當(dāng)repl是一個(gè)字符串時(shí),可以使用\id或者\(yùn)g引用分組,但不能使用編號(hào)0,如下:
2)當(dāng)repl是一個(gè)方法時(shí),這個(gè)方法只接受一個(gè)matchObject對(duì)象作為參數(shù),并放回一個(gè)字符串用于替換
count用于指定最多替換次數(shù),不指定時(shí)全部替換
例程如下:
>>> ptn = re.compile(r"(\w+) (\w+)")
>>> s = "i say, hello world!"
>>> print ptn.sub("replace", s) #使用普通字符串
replace, replace!
>>> print ptn.sub(r"\2 \1", s) #使用\id引用分組
say i, world hello!
>>> def func(m):
... return m.group(1).title() + " " + m.group(2).title()
...
>>> print re.sub(ptn, func, s) #使用方法
I Say, Hello World!
2.9 re.subn(pattern, repl, string[, count])
返回(sub(pattern, repl, string[, count]), 替換次數(shù))
3 正則表達(dá)式的語(yǔ)法規(guī)范
