Python正則表達(dá)式對象如何解決相關(guān)問題
Python正則表達(dá)式對象在我們的使用中有很多問題需要引起我們注意。下面我們就來看看如何進(jìn)行Python正則表達(dá)式對象的相關(guān)技術(shù)應(yīng)用。希望對大家有所幫助。
產(chǎn)生方式:通過
- re.compile(pattern,[flags])回
- match( string[, pos[, endpos]]) ;返回string[pos,endpos]匹配
- pattern的MatchObject
Python代碼
- split( string[, maxsplit = 0])
- findall( string[, pos[, endpos]])
- sub( repl, string[, count = 0])
這幾個函數(shù)和re模塊內(nèi)的相同,只不過是調(diào)用形式有點(diǎn)差別
re.幾個函數(shù)和 正則表達(dá)式對象的幾個函數(shù),功能相同,但同一程序如果
多次用的這些函數(shù)功能,正則表達(dá)式對象的幾個函數(shù)效率高些
matchobject
通過 re.match(……) 和 re.compile(……).match返回
該對象有如下方法和屬性:
方法:
- group( [group1, ...])
- groups( [default])
- groupdict( [default])
- start( [group])
- end( [group])
說明這幾個函數(shù)的***方法,就是舉個例子
- matchObj = re.compile(r”(?P\d+)\.(\d*)”)
- m = matchObj.match(’3.14sss’)
- #m = re.match(r”(?P\d+)\.(\d*)”, ‘3.14sss’)
- print m.group()
- print m.group(0)
- print m.group(1)
- print m.group(2)
- print m.group(1,2)
- print m.group(0,1,2)
- print m.groups()
- print m.groupdict()
- print m.start(2)
- print m.string
輸出如下:
- 3.14
- 3.14
- 3
- 14
- (’3′, ‘14′)
- (’3.14′, ‘3′, ‘14′)
- (’3′, ‘14′)
- {’int’: ‘3′}
- 2
- 3.14sss
所以group() 和group(0)返回,匹配的整個表達(dá)式的字符串,另外group(i) 就是正則表達(dá)式中用第i個“()” 括起來的匹配內(nèi)容 (’3.14′, ‘3′, ‘14′)最能說明問題了。
【編輯推薦】