python正則表達式re模塊詳解
更新時間:2014年06月25日 11:04:02 投稿:hebedich
re 模塊包含對正則表達式的支持,因為曾經系統(tǒng)學習過正則表達式,所以基礎內容略過,直接看 python 對于正則表達式的支持。
快速入門
import re
pattern = 'this'
text = 'Does this text match the pattern?'
match = re.search(pattern, text)
s = match.start()
e = match.end()
print('Found "{0}"\nin "{1}"'.format(match.re.pattern, match.string))
print('from {0} to {1} ("{2}")'.format( s, e, text[s:e]))
執(zhí)行結果:
#python re_simple_match.py
Found "this"
in "Does this text match the pattern?"
from 5 to 9 ("this")
import re
# Precompile the patterns
regexes = [ re.compile(p) for p in ('this', 'that')]
text = 'Does this text match the pattern?'
print('Text: {0}\n'.format(text))
for regex in regexes:
if regex.search(text):
result = 'match!'
else:
result = 'no match!'
print('Seeking "{0}" -> {1}'.format(regex.pattern, result))
執(zhí)行結果:
#python re_simple_compiled.py
Text: Does this text match the pattern?
Seeking "this" -> match!
Seeking "that" -> no match!
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.findall(pattern, text):
print('Found "{0}"'.format(match))
執(zhí)行結果:
#python re_findall.py
Found "ab"
Found "ab"
import re
text = 'abbaaabbbbaaaaa'
pattern = 'ab'
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('Found "{0}" at {1}:{2}'.format(text[s:e], s, e))
執(zhí)行結果:
#python re_finditer.py Found "ab" at 0:2 Found "ab" at 5:7
相關文章
從np.random.normal()到正態(tài)分布的擬合操作
這篇文章主要介紹了從np.random.normal()到正態(tài)分布的擬合操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
python庫lxml在linux和WIN系統(tǒng)下的安裝
這篇內容我們給大家分享了lxml在WIN和LINUX系統(tǒng)下的簡單快速安裝過程,有興趣的朋友參考學習下。2018-06-06

