一篇文章帶你了解python正則表達(dá)式的正確用法
1)在實(shí)際開發(fā)過程中經(jīng)常會(huì)有查找符合某些復(fù)雜規(guī)則的字符串的需要,比如:郵箱、手機(jī)號(hào)碼等,這時(shí)候想匹配或者查找符合某些規(guī)則的字符串就可以使用正則表達(dá)式了。
2)正則表達(dá)式就是記錄文本規(guī)則的代碼
re模塊在Python中需要通過正則表達(dá)式對(duì)字符串進(jìn)行匹配的時(shí)候,可以使用一個(gè) re 模塊
# 導(dǎo)入re模塊import re# 使用match方法進(jìn)行匹配操作result = re.match(正則表達(dá)式,要匹配的字符串)# 如果上一步匹配到數(shù)據(jù)的話,可以使用group方法來提取數(shù)據(jù)result.group()# 導(dǎo)入re模塊import re# 使用match方法進(jìn)行匹配操作result = re.match('test','test.cn')# 獲取匹配結(jié)果info = result.group()print(info)
結(jié)果:test
re.match() 根據(jù)正則表達(dá)式從頭開始匹配字符串?dāng)?shù)據(jù)如果第一個(gè)匹配不成功就會(huì)報(bào)錯(cuò)
匹配單個(gè)字符# 匹配任意一個(gè)字符import reret = re.match('.','x')print(ret.group())ret = re.match('t.o','too')print(ret.group())ret = re.match('o.e','one')print(ret.group())
運(yùn)行結(jié)果:xtooone
2.匹配[ ]中列舉的字符import reret = re.match('[hH]','hello Python')print(ret.group())ret = re.match('[hH]','Hello Python')print(ret.group())
運(yùn)行結(jié)果:hH
3.d匹配數(shù)字,即0-9import reret = re.match('神州d號(hào)','神州6號(hào)')print(ret.group())
運(yùn)行結(jié)果:神州6號(hào)
4.D匹配非數(shù)字,即不是數(shù)字non_obj = re.match('D', 's')print(non_obj .group())
運(yùn)行結(jié)果:s
5.s匹配空白,即 空格,tab鍵match_obj = re.match('hellosworld', 'hello world')print(match_obj .group())
運(yùn)行結(jié)果:hello world
6.S匹配非空白match_obj = re.match('helloSworld', 'hello&world')result = match_obj.group()print(result)
運(yùn)行結(jié)果:hello&world
7.w匹配非特殊字符,即a-z、A-Z、0-9、_、漢字match_obj = re.match('w', 'A')result = match_obj.group()print(result)
運(yùn)行結(jié)果:A
8.W匹配特殊字符,即非字母、非數(shù)字、非漢字match_obj = re.match('W', '&')result = match_obj.group()print(result)
運(yùn)行結(jié)果:&
總結(jié)本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注好吧啦網(wǎng)的更多內(nèi)容!
相關(guān)文章:
1. XML入門的常見問題(二)2. JSP 中request與response的用法詳解3. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫(kù)的方法4. asp中response.write("中文")或者js中文亂碼問題5. phpstudy apache開啟ssi使用詳解6. asp取整數(shù)mod 有小數(shù)的就自動(dòng)加17. asp批量添加修改刪除操作示例代碼8. css代碼優(yōu)化的12個(gè)技巧9. ASP基礎(chǔ)知識(shí)Command對(duì)象講解10. CSS3中Transition屬性詳解以及示例分享
