python正则表达式模块_Python正则表达式函数模块
今天學(xué)習(xí)了Python中有關(guān)正則表達(dá)式的知識(shí)。關(guān)于正則表達(dá)式的語法,不作過多解釋,網(wǎng)上有許多學(xué)習(xí)的資料。這里主要介紹python中常用的正則表達(dá)式處理函數(shù)。
方法/屬性
作用
match()
決定 RE
是否在字符串剛開始的位置匹配
search()
掃描字符串,找到這個(gè) RE
匹配的位置
findall()
找到 RE
匹配的所有子串,并把它們作為一個(gè)列表返回
finditer()
找到 RE
匹配的所有子串,并把它們作為一個(gè)迭代器返回
match() 函數(shù)只檢查 RE
是否在字符串開始處匹配,而 search() 則是掃描整個(gè)字符串。
match()
只報(bào)告一次成功的匹配,它將從 0 處開始;如果匹配不是從 0 開始的,match() 將不會(huì)報(bào)告它。
search()
將掃描整個(gè)字符串,并報(bào)告它找到的第一個(gè)匹配。
match()、seerch()、finditer()如果匹配成功則返回一個(gè)Match
Object對象,該對象有以下屬性、方法:
方法/屬性
作用
group()
返回被 RE
匹配的字符串
start()
返回匹配開始的位置
end()
返回匹配結(jié)束的位置
span()
返回一個(gè)元組包含匹配
(開始,結(jié)束) 的位置
group()
返回re整體匹配的字符串,可以一次輸入多個(gè)組號(hào),對應(yīng)組號(hào)匹配的字符串。
1.
group()返回re整體匹配的字符串,
2. group (n,m)
返回組號(hào)為n,m所匹配的字符串,如果組號(hào)不存在,則返回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()
方法返回一個(gè)包含正則表達(dá)式中所有小組字符串的元組,從 1 到
所含的小組號(hào),通常groups()不需要參數(shù),返回一個(gè)元組,元組中的元就是正則表達(dá)式中定義的組。
#!python
>>> p = re.compile('(a(b)c)d')
>>> m = p.match('abcd')
>>> m.groups()
('abc', 'b')
使用索引取得相應(yīng)的組內(nèi)容,例如:m.groups()[0]
p2=re.compile(r'''(\d)+\w''',re.X)
>>> p2.match('123a
b12123c').group() # re正則表達(dá)式
'(\d)+\w匹配的字符串
'123a'
>>> p2.match('123a
b12123c').group(0)
'123a'
>>> p2.match('123a b12123c').group(1)
#返回正則表達(dá)式中第一個(gè)小組即(\d)所匹配的字符串
'3'
>>> p2.match('123a b12
123c').groups()
('3',)
re.match ,從字符串開頭匹配,返回一個(gè)Match
Object,或None
re.match
嘗試從字符串的開始匹配一個(gè)模式,如:下面的例子匹配第一個(gè)單詞。
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的函數(shù)原型為:re.match(pattern,
string, flags)
第一個(gè)參數(shù)是正則表達(dá)式,這里為"(\w+)\s",如果匹配成功,則返回一個(gè)Match,否則返回一個(gè)None;
第二個(gè)參數(shù)表示要匹配的字符串;
第三個(gè)參數(shù)是標(biāo)致位,用于控制正則表達(dá)式的匹配方式,如:是否區(qū)分大小寫,多行匹配等等。
方法/屬性
作用
group()
返回被 RE
匹配的字符串
start()
返回匹配開始的位置
end()
返回匹配結(jié)束的位置
span()
返回一個(gè)元組包含匹配
(開始,結(jié)束) 的位置
re.search 在字符串內(nèi)查找匹配,找到第一個(gè)匹配,返回Match Object,或None
re.search函數(shù)會(huì)在字符串內(nèi)查找模式匹配,直到找到第一個(gè)匹配然后返回,如果字符串沒有匹配,則返回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的函數(shù)原型為: re.search(pattern,
string, flags)
每個(gè)參數(shù)的含意與re.match一樣。
re.match與re.search的區(qū)別:re.match只匹配字符串的開始,如果字符串開始不符合正則表達(dá)式,則匹配失敗,函數(shù)返回None;而re.search匹配整個(gè)字符串,直到找到一個(gè)匹配。
re.sub 替換所有的匹配項(xiàng),返回一個(gè)替換后的字符串,如果匹配失敗,返回原字符串
re.sub用于替換字符串中的匹配項(xiàng)。下面一個(gè)例子將字符串中的空格 '
' 替換成 '-' :
import re text
= "JGood is a handsome boy, he is cool, clever, and so on..." print
re.sub(r'\s+', '-', text)
re.sub的函數(shù)原型為:re.sub(pattern, repl,
string, count)
其中第二個(gè)函數(shù)是替換后的字符串;本例中為'-'
第四個(gè)參數(shù)指替換個(gè)數(shù)。默認(rèn)為0,表示每個(gè)匹配項(xiàng)都替換。
re.sub還允許使用函數(shù)對匹配項(xiàng)的替換進(jìn)行復(fù)雜的處理。如:re.sub(r'\s',
lambda m: '[' + m.group(0) + ']', text, 0);將字符串中的空格' '替換為'[
]'。
sub()
方法提供一個(gè)替換值,可以是字符串或一個(gè)函數(shù),和一個(gè)要被處理的字符串
當(dāng)使用模塊級(jí)的 re.sub()
函數(shù)時(shí),模式作為第一個(gè)參數(shù)。模式也許是一個(gè)字符串或一個(gè) `RegexObject`;如果你需要指定正則表達(dá)式標(biāo)志,你必須要么使用
`RegexObject` 做第一個(gè)參數(shù),或用使用模式內(nèi)嵌修正器,如 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( )
相同,但返回新的字符串和替換次數(shù)
re.subn('i','I','Paris in the the spring') # ('ParIs In
the the sprIng', 3)
空匹配只有在它們沒有緊挨著前一個(gè)匹配時(shí)才會(huì)被替換掉。
#!python
>>> p =
re.compile('x*')
>>> p.sub('-',
'abxd')
'-a-b-d-'
re.split 以列表形式返回分割的字符串
可以使用re.split來分割字符串,如:re.split(r'\s+',
text);將字符串按空格分割成一個(gè)單詞列表。
split(string [, maxsplit = 0])
你可以通過設(shè)置 maxsplit
值來限制分片數(shù)。當(dāng) maxsplit 非零時(shí),最多只能有 maxsplit
個(gè)分片,字符串的其余部分被做為列表的最后部分返回。在下面的例子中,定界符可以是非數(shù)字字母字符的任意序列。
#!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().']
有時(shí),你不僅對定界符之間的文本感興趣,也需要知道定界符是什么。定界符可以是非數(shù)字字母字符的任意序列
,如果捕獲括號(hào)在 RE中使用,那么它們(定界符)的值也會(huì)當(dāng)作列表的一部分返回。比較下面的調(diào)用:
re.split("([ab])","carbs") #
['c', 'a', 'r', 'b', 's'] 定界符是a或b,結(jié)果返回界定符a、b。
re.split("([ab]#)", "carbs")
# ['carbs'] 定界符是a#或b#,結(jié)果
['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) #結(jié)果:['JGood', 'cool']
print re.findall(r'(\w)*oo(\w)*',text) # ()表示子表達(dá)式 結(jié)果:[('G', 'd'),
('c', 'l')]
在 Python 2.2中,也可以用 finditer()
方法。
#!python
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
>>> for match in iterator:
... print match.group() ,match.span()
...
12 (0, 2)
11 (22, 24)
10 (29, 31)
re.compile
可以把正則表達(dá)式編譯成一個(gè)正則表達(dá)式對象。可以把那些經(jīng)常使用的正則表達(dá)式編譯成正則表達(dá)式對象,這樣可以提高一定的效率。下面是一個(gè)正則表達(dá)式對象的一個(gè)例子:
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'的單詞用[]括起來。
轉(zhuǎn)自:http://www.python8.org/a/fenleiwenzhang/yuyanjichu/2009/0901/150.html
總結(jié)
以上是生活随笔為你收集整理的python正则表达式模块_Python正则表达式函数模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python实现排序_python实现以
- 下一篇: 光源时间_天哪!你们居然都错了!D65光