Python正則表達式指南下半部

2.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時指定匹配模式。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# encoding: UTF-8
import re
 
# 將正則表達式編譯成Pattern對象
pattern = re.compile(r'world')
 
# 使用search()查找匹配的子串,不存在能匹配的子串時將返回None
# 這個例子中使用match()無法成功匹配
match = pattern.search('hello world!')
 
if match:
    # 使用Match獲得分組信息
    print match.group()
 
### 輸出 ###
# world

  3.split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]): 

  按照能夠匹配的子串將string分割後返回列表。maxsplit用於指定最大分割次數,不指定將全部分割。

1
2
3
4
5
6
7
import re
 
p = re.compile(r'\d+')
print p.split('one1two2three3four4')
 
### output ###
# ['one', 'two', 'three', 'four', '']

  4.findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]): 

  搜索string,以列表形式返回全部能匹配的子串。

1
2
3
4
5
6
7
import re
 
p = re.compile(r'\d+')
print p.findall('one1two2three3four4')
 
### output ###
# ['1', '2', '3', '4']

  5.finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]): 

  搜索string,返回一個順序訪問每一個匹配結果(Match對象)的迭代器 。

1
2
3
4
5
6
7
8
import re
 
p = re.compile(r'\d+')
for m in p.finditer('one1two2three3four4'):
    print m.group(),
 
### output ###
# 1 2 3 4

  6.sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]): 

  使用repl替換string中每一個匹配的子串後返回替換後的字符串。

  當repl是一個字符串時,可以使用\id或\g<id>、\g<name>引用分組,但不能使用編號0。

  當repl是一個方法時,這個方法應當只接受一個參數(Match對象),並返回一個字符串用於替換(返回的字符串中不能再引用分組)。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章