Python 模塊學習:re模塊


今天學習了Python中有關正則表達式的知識。關於正則表達式的語法,不作過多解釋,網上有許多學習的資料。這里主要介紹Python中常用的正則表達式處理函數。

 

方法/屬性 作用
match() 決定 RE 是否在字符串剛開始的位置匹配
search() 掃描字符串,找到這個 RE 匹配的位置
findall() 找到 RE 匹配的所有子串,並把它們作為一個列表返回
finditer() 找到 RE 匹配的所有子串,並把它們作為一個迭代器返回

 

match() 函數只檢查 RE 是否在字符串開始處匹配,而 search() 則是掃描整個字符串。

match() 只報告一次成功的匹配,它將從 0 處開始;如果匹配不是從 0 開始的,match() 將不會報告它。

search() 將掃描整個字符串,並報告它找到的第一個匹配。


match()、seerch()、finditer()如果匹配成功則返回一個Match Object對象,該對象有以下屬性、方法:

 

方法/屬性 作用
group() 返回被 RE 匹配的字符串
start() 返回匹配開始的位置
end() 返回匹配結束的位置
span() 返回一個元組包含匹配 (開始,結束) 的位置

 

 

 

group() 返回re整體匹配的字符串,可以一次輸入多個組號,對應組號匹配的字符串。

1. group()返回re整體匹配的字符串,

2. group (n,m) 返回組號為n,m所匹配的字符串,如果組號不存在,則返回indexError異常

 

#!python
>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.group(0)
'abcd'
>>> m.group(1)
'abc'
>>> m.group(2)
'b'

 

groups() 方法返回一個包含 正則表達式中所有小組字符串的元組,從 1 到 所含的小組號, 通常groups()不需要參數,返回一個元組,元組中的元就是正則表達式中定義的組。

 

#!python
>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.groups()
('abc', 'b')

使用索引取得相應的組內容,例如:m.groups()[0]

 

p2=re.compile(r'''(\d)+\w''',re.X)  

>>> p2.match('123a b12123c').group()   # re正則表達式 '(\d)+\w匹配的字符串

'123a'

>>> p2.match('123a b12123c').group(0)

'123a'

>>> p2.match('123a b12123c').group(1)  #返回正則表達式中第一個小組即(\d)所匹配的字符串

'3'

>>> p2.match('123a b12 123c').groups() 
('3',)

re.match ,從字符串開頭匹配,返回一個Match Object,或None

  re.match 嘗試從字符串的開始匹配一個模式,如:下面的例子匹配第一個單詞。

 

復制代碼
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.match(r"(\w+)\s", text)
if m:
print m.group(0), '\n', m.group(1)
else:
print 'not match'  
復制代碼

re.match的函數原型為:re.match(pattern, string, flags)

第一個參數是正則表達式,這里為"(\w+)\s",如果匹配成功,則返回一個Match,否則返回一個None;

第二個參數表示要匹配的字符串;

第三個參數是標致位,用於控制正則表達式的匹配方式,如:是否區分大小寫,多行匹配等等。

 

 

方法/屬性 作用
group() 返回被 RE 匹配的字符串
start() 返回匹配開始的位置
end() 返回匹配結束的位置
span() 返回一個元組包含匹配 (開始,結束) 的位置

 

re.search  在字符串內查找匹配,找到第一個匹配,返回Match Object,或None

  re.search函數會在字符串內查找模式匹配,直到找到第一個匹配然后返回,如果字符串沒有匹配,則返回None。

 

復制代碼
import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
m = re.search(r'\shan(ds)ome\s', text)
if m:
print m.group(0), m.group(1)
else:
print 'not search'  
復制代碼

re.search的函數原型為: re.search(pattern, string, flags)

每個參數的含意與re.match一樣。 

re.match與re.search的區別:re.match只匹配字符串的開始,如果字符串開始不符合正則表達式,則匹配失敗,函數返回None;而re.search匹配整個字符串,直到找到一個匹配。

re.sub   替換所有的匹配項,返回一個替換后的字符串,如果匹配失敗,返回原字符串

  re.sub用於替換字符串中的匹配項。下面一個例子將字符串中的空格 ' ' 替換成 '-' : 

 

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
print re.sub(r'\s+', '-', text) 

 re.sub的函數原型為:re.sub(pattern, repl, string, count)

其中第二個函數是替換后的字符串;本例中為'-'

第四個參數指替換個數。默認為0,表示每個匹配項都替換。

re.sub還允許使用函數對匹配項的替換進行復雜的處理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);將字符串中的空格' '替換為'[ ]'。

 

sub() 方法提供一個替換值,可以是字符串或一個函數,和一個要被處理的字符串

 

當使用模塊級的 re.sub() 函數時,模式作為第一個參數。模式也許是一個字符串或一個 `RegexObject`;如果你需要指定正則表達式標志,你必須要么使用 `RegexObject` 做第一個參數,或用使用模式內嵌修正器,如 sub("(?i)b+", "x", "bbbb BBBB") returns 'x x'。 

 

import re

def hexrepl( match ):
     "Return the hex string for a decimal number"
     value = int( match.group() )
     return hex(value)

p = re.compile(r'\d+')

print p.sub(hexrepl, 'Call 65490 for printing, 49152 for user code.')
#Call 0xffd2 for printing, 0xc000 for user code.

 

 


import re

text = "JGood is a handsome boy, he is cool, clever, and so on..."

print re.sub(r'\s+', '-', text)
#JGood-is-a-handsome-boy,-he-is-cool,-clever,-and-so-on...

print re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text)
#JGood[ ]is[ ]a[ ]handsome[ ]boy,[ ]he[ ]is[ ]cool,[ ]clever,[ ]and[ ]so[ ]on...

 

print re.sub(r'a', lambda m: '[' + m.group(0) + ']', text) #在a的兩邊加[ ],也可以用string.replace()

#JGood is [a] h[a]ndsome boy, he is cool, clever, [a]nd so on...

 

subn ( )  與 sub( ) 相同,但返回新的字符串和替換次數

print re.subn('i','I','Paris in the the spring')  # ('ParIs In the the sprIng', 3)

 

空匹配只有在它們沒有緊挨着前一個匹配時才會被替換掉。

#!python

>>> p = re.compile('x*')

>>> p.sub('-', 'abxd')

'-a-b-d-'

 

re.split     以列表形式返回分割的字符串

  可以使用re.split來分割字符串,如:re.split(r'\s+', text);將字符串按空格分割成一個單詞列表。

     

split(string [, maxsplit = 0])

 

你可以通過設置 maxsplit 值來限制分片數。當 maxsplit 非零時,最多只能有 maxsplit 個分片,字符串的其余部分被做為列表的最后部分返回。在下面的例子中,定界符可以是非數字字母字符的任意序列。

#!python
>>> p = re.compile(r'\W+')
>>> p.split('This is a test, short and sweet, of split().')
['This', 'is', 'a', 'test', 'short', 'and', 'sweet', 'of', 'split', '']
>>> p.split('This is a test, short and sweet, of split().', 3)
['This', 'is', 'a', 'test, short and sweet, of split().']

有時,你不僅對定界符之間的文本感興趣,也需要知道定界符是什么。定界符可以是非數字字母字符的任意序列 ,如果捕獲括號在 RE中使用,那么它們(定界符)的值也會當作列表的一部分返回。比較下面的調用:

 

re.split("([ab])","carbs")  #   ['c', 'a', 'r', 'b', 's']     定界符是a或b,結果返回界定符a、b。

re.split("([ab]#)", "carbs")  #  ['carbs']   定界符是a#或b#,結果 ['carbs'] 


#!python
>>> p = re.compile(r'\W+')
>>> p2 = re.compile(r'(\W+)')
>>> p.split('This... is a test.')
['This', 'is', 'a', 'test', '']
>>> p2.split('This... is a test.')
['This', '... ', 'is', ' ', 'a', ' ', 'test', '.', '']

re.findall  以列表形式返回所有匹配的字符串

  re.findall可以獲取字符串中所有匹配的字符串。如:re.findall(r'\w*oo\w*', text);獲取字符串中,包含'oo'的所有單詞。

      

         (pattern) 匹配 pattern並獲取這一匹配


       import re

       text = "JGood is a  handsome boy,he is handsome and cool,clever,and so on ...."


        print re.findall(r'\w*oo\w*',text) #結果:['JGood', 'cool']

       print re.findall(r'(\w)*oo(\w)*',text) # ()表示子表達式 結果:[('G', 'd'), ('c', 'l')]

 

 

在 Python 2.2中,也可以用 finditer() 方法。

#!python
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print match.group() , match.span()
...     
12 (0, 2)
11 (22, 24)
10 (29, 31)


re.compile

  可以把正則表達式編譯成一個正則表達式對象。可以把那些經常使用的正則表達式編譯成正則表達式對象,這樣可以提高一定的效率。下面是一個正則表達式對象的一個例子:

 

import re
text = "JGood is a handsome boy, he is cool, clever, and so on..."
regex = re.compile(r'\w*oo\w*')
print regex.findall(text)   #查找所有包含'oo'的單詞
print regex.sub(lambda m: '[' + m.group(0) + ']', text) #將字符串中含有'oo'的單詞用[]括起來。

轉自:http://www.python8.org/a/fenleiwenzhang/yuyanjichu/2009/0901/150.html

 
0


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM