目錄
文章所屬專區(qū) Python學(xué)習(xí)
前言
本章節(jié)主要說明Python的正則表達式。
正則表達式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配。
re.match函數(shù)
re.match 嘗試從字符串的起始位置匹配一個模式,如果不是起始位置匹配成功的話,match() 就返回 none。
語法:
re.match(pattern, string, flags=0)
參數(shù)說明:
正則表達式可選標志
實例
#!/usr/bin/python
import re
line = "Cats are smarter than dogs"
matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if matchObj:
print "matchObj.group() : ", matchObj.group()
print "matchObj.group(1) : ", matchObj.group(1)
print "matchObj.group(2) : ", matchObj.group(2)
else:
print "No match!!"
多行匹配,大小寫不敏感,“”are“”的語句
re.search方法
re.search 掃描整個字符串并返回第一個成功的匹配。
語法:
re.search(pattern, string, flags=0)
參數(shù)說明:
實例:
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I)
if searchObj:
print "searchObj.group() : ", searchObj.group()
print "searchObj.group(1) : ", searchObj.group(1)
print "searchObj.group(2) : ", searchObj.group(2)
else:
print "Nothing found!!"
re.match與re.search的區(qū)別
re.match只匹配字符串的開始,如果字符串開始不符合正則表達式,則匹配失敗,函數(shù)返回None;而re.search匹配整個字符串,直到找到一個匹配。
#!/usr/bin/python
import re
line = "Cats are smarter than dogs";
matchObj = re.match( r'dogs', line, re.M|re.I)
if matchObj:
print "match --> matchObj.group() : ", matchObj.group()
else:
print "No match!!"
matchObj = re.search( r'dogs', line, re.M|re.I)
if matchObj:
print "search --> searchObj.group() : ", matchObj.group()
else:
print "No match!!"
返回:
No match!! #match在字符串開始沒有匹配到字符 返回false
search --> searchObj.group() : dogs #search在整個字符串匹配到了字符,返回true
參考
菜鳥教程-Python文章來源:http://www.zghlxwxcb.cn/news/detail-814000.html
給個三連吧 謝謝謝謝謝謝了文章來源地址http://www.zghlxwxcb.cn/news/detail-814000.html
到了這里,關(guān)于【Python學(xué)習(xí)】Python學(xué)習(xí)21- 正則表達式(1)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!