做好一件事情不難,只要敢于邁出第一步,然后不斷邁出下一步就行了.小馬哥也會(huì)把每一個(gè)專題文章從最簡(jiǎn)單的內(nèi)容開(kāi)始發(fā)布,每天不斷迭代修改,添加內(nèi)容.用最簡(jiǎn)單的方式積累和傳遞有用的東西.
本文重點(diǎn): 介紹Python針對(duì)正則表達(dá)式的常用函數(shù)
import re
#(1)使用match()方法匹配字符串
# match()在字符串的起始部分進(jìn)行匹配: 如果匹配成功,返回一個(gè)匹配對(duì)象;如果匹配失敗,返回一個(gè)None
# group()方法能夠用于顯示成功的匹配
result = re.match(pattern ='hello',string ='hello python')????# 返回一個(gè)re.Match對(duì)象
if result is not None:
????print(result.group())#返回成功的匹配
#match特點(diǎn): 在字符串的起始位置開(kāi)始匹配,即使字符串比模式長(zhǎng)也會(huì)match成功,
#(2)使用search()方法在字符串中查找
# 不是所有的字符串都是在開(kāi)頭部分進(jìn)行匹配,更多的情況是搜索字符串中是否包含指定的模式/模板
# search方法與match方法的不同在于,match是在字符串的開(kāi)頭進(jìn)行匹配,而search可以搜索字符串的任意位置,只有遇到一次匹配就返回匹配對(duì)象,否則返回None
#search()方法會(huì)自左到右一次匹配字符串,直到第一次出現(xiàn)的位置
m = re.match('python','hello python')
if m is not None:print('Match(): ',m.group())
s = re.search('python','hello python')
if s is not None:print('Search(): ',s.group())
#(3)匹配對(duì)個(gè)模式: 擇一匹配符號(hào)的使用
patterns ='Mark|Jack|Pony'
result = re.match(patterns,'Pony Ma')
if result is not None:
????print(result.group())
result = re.search(patterns,'Alibaba,Jack Ma')
if result is not None:
????print(result.group())
#(4)匹配任何單個(gè)字符
#注意不能匹配換行符或者非字符(空字符串)
msg ='hello go'
pattern ='g.'
result = re.search(pattern,msg)
if result is not None:
????print(result)
????print(result.group())
msg2 ='hello \nyou'
pattern ='.you'
result = re.search(pattern,msg2)
if result is None:
????print(result)
#注意: 如果想匹配標(biāo)點(diǎn):".",要通過(guò)使用轉(zhuǎn)移符號(hào)\來(lái)解決
msg3 ='nlgc@163.com'
pattern ='\.com'? #如果一定要匹配一個(gè)".",那么要加上\,否則,就會(huì)任意符合條件的字符串都會(huì)被匹配到
result = re.search(pattern,msg3)
if result is not None:
????print(result.group())
#(5)創(chuàng)建字符集
pattern ='[abcd]'
msg ='x'
result = re.match(pattern,msg)
print(type(result))
#(6)特殊字符( ., \d, \w, \s)與分組以及頻數(shù)(+, *, ?)的使用
#匹配電子郵件xxxxx@yyyyy.com
pattern ='\w+@(.)*?.com'
email ='mark123@yeah.163.com'
result = re.match(pattern,email)
print(type(result))
#(7)匹配字符串的起始和結(jié)尾以及單詞邊界
#一般這種位置用于search()中,在字符串中搜索出符合模式的字符串,因?yàn)閙atch()就是在字符串的起始位置開(kāi)始的
msg ='Lost years are worse than lost dollars.'
pattern ='^Lost(.*)$'
result = re.match(pattern,msg)
if result is not None:
????print(result.groups())
#(8)使用findall()查找每一次出現(xiàn)的位置
#findall(): 查詢字符串中某個(gè)正則表達(dá)式模式全部匹配情況,結(jié)果包含在列表里面返回
msg ='hello1 python,hello2 java,hello3 go'
pattern ='hello\d'
result = re.findall(pattern,msg)
print(result)
#(9)使用finditer()更加節(jié)省內(nèi)存
#(10)使用sub()和subn()替換字符串中符合模式的子字符串
#subn()和sub()功能一樣,但是多了一個(gè)返回被替換的個(gè)數(shù)
#將welcome變量里面的name換做name變量里面的字符串Mark
name ='Mark'
welcome ='Good morning,name!'
result = re.sub('name',name,welcome)
print(result)
result_plus = re.subn('name',name,welcome)
print(result_plus)#同sub()一樣會(huì)返回替換完成之后的句子,但是作為元組,還會(huì)返回被修改的模式的次數(shù)
#(11)split()分割字符串
data ='郵政編碼:100000'
pattern =':'
result = re.split(pattern,data)
print(result)