Python正則表達式對象如何解決相關問題
Python正則表達式對象在我們的使用中有很多問題需要引起我們注意。下面我們就來看看如何進行Python正則表達式對象的相關技術應用。希望對大家有所幫助。
產生方式:通過
- 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])
這幾個函數和re模塊內的相同,只不過是調用形式有點差別
re.幾個函數和 正則表達式對象的幾個函數,功能相同,但同一程序如果
多次用的這些函數功能,正則表達式對象的幾個函數效率高些
matchobject
通過 re.match(……) 和 re.compile(……).match返回
該對象有如下方法和屬性:
方法:
- group( [group1, ...])
- groups( [default])
- groupdict( [default])
- start( [group])
- end( [group])
說明這幾個函數的***方法,就是舉個例子
- 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)返回,匹配的整個表達式的字符串,另外group(i) 就是正則表達式中用第i個“()” 括起來的匹配內容 (’3.14′, ‘3′, ‘14′)最能說明問題了。
【編輯推薦】