python_ re模块学习
生活随笔
收集整理的這篇文章主要介紹了
python_ re模块学习
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
字符匹配(普通字符,元字符):
普通字符:大多數字符和字母都會和自身匹配
re.findall('alvin','yuanaleSxalexwupeiqi')
['alvin']
元字符之. ^ $ * + ? { }
import reret=re.findall('a..in','helloalvin') print(ret)#['alvin']ret=re.findall('^a...n','alvinhelloawwwn') print(ret)#['alvin']ret=re.findall('a...n$','alvinhelloawwwn') print(ret)#['awwwn']ret=re.findall('a...n$','alvinhelloawwwn') print(ret)#['awwwn']ret=re.findall('abc*','abcccc')#貪婪匹配[0,+oo] print(ret)#['abcccc']ret=re.findall('abc+','abccc')#[1,+oo] print(ret)#['abccc']ret=re.findall('abc?','abccc')#[0,1] print(ret)#['abc']ret=re.findall('abc{1,4}','abccc') print(ret)#['abccc'] 貪婪匹配ret=re.findall('abc*?','abcccccc') print(ret)#['ab']元字符之字符集[]:
#--------------------------------------------字符集[] ret=re.findall('a[bc]d','acd') print(ret)#['acd']ret=re.findall('[a-z]','acd') print(ret)#['a', 'c', 'd']ret=re.findall('[.*+]','a.cd+') print(ret)#['.', '+']#在字符集里有功能的符號: - ^ \ret=re.findall('[1-9]','45dha3') print(ret)#['4', '5', '3']ret=re.findall('[^ab]','45bdha3') print(ret)#['4', '5', 'd', 'h', '3']ret=re.findall('[\d]','45bdha3') print(ret)#['4', '5', '3']元字符之轉義符\
反斜杠后邊跟元字符去除特殊功能,比如.
反斜杠后邊跟普通字符實現特殊功能,比如\d
\d 匹配任何十進制數;它相當于類 [0-9]。
\D 匹配任何非數字字符;它相當于類 [^0-9]。
\s 匹配任何空白字符;它相當于類 [ \t\n\r\f\v]。
\S 匹配任何非空白字符;它相當于類 [^ \t\n\r\f\v]。
\w 匹配任何字母數字字符;它相當于類 [a-zA-Z0-9]。
\W 匹配任何非字母數字字符;它相當于類 [^a-zA-Z0-9]
\b 匹配一個特殊字符邊界,比如空格 ,&,#等
元字符之分組()
m = re.findall(r'(ad)+', 'add') print(m)ret=re.search('(?P<id>\d{2})/(?P<name>\w{3})','23/com') print(ret.group())#23/com print(ret.group('id'))#23元字符之|
ret=re.search('(ab)|\d','rabhdg8sd') print(ret.group())#ab re模塊下的常用方法import re #1 re.findall('a','alvin yuan') #返回所有滿足匹配條件的結果,放在列表里 #2 re.search('a','alvin yuan').group() #函數會在字符串內查找模式匹配,只到找到第一個匹配然后返回一個包含匹配信息的對象,該對象可以# 通過調用group()方法得到匹配的字符串,如果字符串沒有匹配,則返回None。#3 re.match('a','abc').group() #同search,不過盡在字符串開始處進行匹配#4 ret=re.split('[ab]','abcd') #先按'a'分割得到''和'bcd',在對''和'bcd'分別按'b'分割 print(ret)#['', '', 'cd']#5 ret=re.sub('\d','abc','alvin5yuan6',1) print(ret)#alvinabcyuan6 ret=re.subn('\d','abc','alvin5yuan6') print(ret)#('alvinabcyuanabc', 2)#6 obj=re.compile('\d{3}') ret=obj.search('abc123eeee') print(ret.group())#123import re ret=re.finditer('\d','ds3sy4784a') print(ret) #<callable_iterator object at 0x10195f940>print(next(ret).group()) print(next(ret).group()) 注意:import reret=re.findall('www.(baidu|oldboy).com','www.oldboy.com') print(ret)#['oldboy'] 這是因為findall會優先把匹配結果組里內容返回,如果想要匹配結果,取消權限即可ret=re.findall('www.(?:baidu|oldboy).com','www.oldboy.com') print(ret)#['www.oldboy.com']轉載于:https://blog.51cto.com/357712148/2139521
總結
以上是生活随笔為你收集整理的python_ re模块学习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Promise 化回调式函数
- 下一篇: Eclipse Spring Boot实