使用形式化模式搜索和修改文本逃顶。python中正則表達式通過re模塊使用語法以per語言語法為基礎(chǔ)弊决。
查找文本中的模式
re最常見的用法就是搜索文本中的模式危融。 search()函數(shù)取模式和要掃描的文本作為輸入陵刹,如果找到這個模式則返回一個match對象啃洋。如果未找到模式,search()將返回None遍希。
每個match對象包含有關(guān)匹配性質(zhì)的性質(zhì)的信息等曼,包括原輸入字符串,使用的正則表達式凿蒜,以及模式在原字符串中出現(xiàn)的位置。
start()可以給出字符串中的相應(yīng)索引胁黑,
end()方法給出字符串中的相應(yīng)索引废封,指示與模式匹配的文本在字符串中出現(xiàn)位置
例如:
#!/usr/bin/env python
import re
pattern = 'this'
text = 'Does this text matcht the pattern?'
match = re.search(pattern,text)
s = match.start()
e = match.end()
print 'start in %s' % s
print 'end in %s' % e
print 'Found "%s"\nin "%s"\nfrom %d to %d ("%s")' % (match.re.pattern,match.string,s,e,text[s:e])
print text
print text[s:e]
re包含一些高級模塊用于處理作為文本字符串的正則表達式,不過對于對于過程序頻繁使用的表達式丧蘸,編譯這些表達式會更高效漂洋。compile()會把正則表達式編譯成一個RegexObject對象如下:
search()用來查找字面量文本,字符串的單個實例
力喷,findall()函數(shù)返回輸入中與模式匹配而不重疊的所有子串刽漂。
可以使用5種方式表示重復(fù),表示方法如下:
× 表示0次或多次
(允許一個模式重復(fù)0次弟孟,匹配不存在情況
- 表示至少匹配一次
贝咙? 表示0次或一次
{n} 表示出現(xiàn)指定的次數(shù)
{m,n} 表示至少出現(xiàn)m次,最多出現(xiàn)m次
[ab] 表示a或b
[^] 表示禁止查找相應(yīng)字符
python中還可以使用轉(zhuǎn)譯 碼拂募,主要轉(zhuǎn)譯碼如下:
\d 一個數(shù)字
\D 一個非數(shù)字
\s 一個空白符
\S 一個非空白符
\w 一個字母數(shù)字
\W 一個非字母數(shù)字
^ 字符串或行的開始
$ 字符菜或行的結(jié)束
\A 字符串開始
\Z 字符串結(jié)束
\b 一個單詞開頭或末尾的空串
\B 不再單詞開頭或結(jié)尾的空串
限制搜索
搜索可以使用re.match和re.search()庭猩,
re.match()
僅當(dāng)搜索對象位于字符串最前面時才能有效識別,而search可以隨時找到他陈症。
用組解析匹配
使用group()可以得到某個組織的匹配蔼水,如果使用分組來查找字符串的各部分不過結(jié)果中并不需要某些與組匹配的部分,此時group()會很有用录肯。
示例代碼如下:
text = 'this is some text -- with punctuation.'
>>> print 'input text :', text
input text : this is some text -- with punctuation.
>>> regex = re.compile(r'(\bt\w+)\W+(\w+)')
>>> match = regex.search(text)
>>> print 'entire match :', match.group(0)
entire match : this is
>>> print 'entire match :', match.group(1)
entire match : this
>>> print 'entire match :', match.group(2)
entire match : is
>>> print 'entire match :', match.group(3)
entire match :
第0組表示與整個表達式匹配的字符串趴腋,子組按其左小括號在表達式中出現(xiàn)順序重1開始標(biāo)號。
分組可以設(shè)置一個名字稱命名組語法:(?P<name>pattern)