標籤:span 一個 字元 輸出 odi x11 方法 簡單的 tle
所使用模組:re
對於Python使用正則一般都是先將Regex的字串形式編譯然後進行執行個體化。如下進行一個最簡單的正則匹配
#encoding=utf-8#by defimport repattern = re.compile(r‘hello‘) #執行個體化if re.match(‘hello world‘): #使用pattern去匹配字串 print "true"else: print "false"
輸出:true
因為其已經匹配到了所以輸出true
re模組除了擁有compile這個方法以外還有
執行個體方法[ | re模組方法]:
- match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):
這個方法將從string的pos下標處起嘗試匹配pattern;如果pattern結束時仍可匹配,則返回一個Match對象;如果匹配過程中pattern無法匹配,或者匹配未結束就已到達endpos,則返回None。
pos和endpos的預設值分別為0和len(string);re.match()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。
注意:這個方法並不是完全符合。當pattern結束時若string還有剩餘字元,仍然視為成功。想要完全符合,可以在運算式末尾加上邊界匹配符‘$‘。
樣本參見2.1小節。
- search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]):
這個方法用於尋找字串中可以匹配成功的子串。從string的pos下標處起嘗試匹配pattern,如果pattern結束時仍可匹配,則返回一個Match對象;若無法匹配,則將pos加1後重新嘗試匹配;直到pos=endpos時仍無法匹配則返回None。
pos和endpos的預設值分別為0和len(string));re.search()無法指定這兩個參數,參數flags用於編譯pattern時指定匹配模式。
| 12345678910111213141516 |
# encoding: UTF-8 import re # 將Regex編譯成Pattern對象 pattern = re.compile(r‘world‘) # 使用search()尋找匹配的子串,不存在能匹配的子串時將返回None # 這個例子中使用match()無法成功匹配 match = pattern.search(‘hello world!‘) if match: # 使用Match獲得分組資訊 print match.group() ### 輸出 ### # world |
- split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。
| 1234567 |
import re p = re.compile(r‘\d+‘)print p.split(‘one1two2three3four4‘) ### output #### [‘one‘, ‘two‘, ‘three‘, ‘four‘, ‘‘] |
- findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜尋string,以列表形式返回全部能匹配的子串。
| 1234567 |
import re p = re.compile(r‘\d+‘)print p.findall(‘one1two2three3four4‘) ### output #### [‘1‘, ‘2‘, ‘3‘, ‘4‘] |
- finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜尋string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器。
| 12345678 |
import re p = re.compile(r‘\d+‘)for m in p.finditer(‘one1two2three3four4‘): print m.group(), ### output #### 1 2 3 4 |
- sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替換string中每一個匹配的子串後返回替換後的字串。
當repl是一個字串時,可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。
當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字串用於替換(返回的字串中不能再引用分組)。
count用於指定最多替換次數,不指定時全部替換。
| 123456789101112131415 |
import re p = re.compile(r‘(\w+) (\w+)‘)s = ‘i say, hello world!‘ print p.sub(r‘\2 \1‘, s) def func(m): return m.group(1).title() + ‘ ‘ + m.group(2).title() print p.sub(func, s) ### output #### say i, world hello!# I Say, Hello World! |
- subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替換次數)。
| 123456789101112131415 |
import re p = re.compile(r‘(\w+) (\w+)‘)s = ‘i say, hello world!‘ print p.subn(r‘\2 \1‘, s) def func(m): return m.group(1).title() + ‘ ‘ + m.group(2).title() print p.subn(func, s) ### output #### (‘say i, world hello!‘, 2)# (‘I Say, Hello World!‘, 2) |
pythonRegex