python正則表達

來源:互聯網
上載者:User

標籤:ima   5.0   包含   string   例子   print   \n   tail   copy   

十三 re模組

一:什麼是正則?

 正則就是用一些具有特殊含義的符號組合到一起(稱為Regex)來描述字元或者字串的方法。或者說:正則就是用來描述一類事物的規則。(在Python中)它內嵌在Python中,並通過 re 模組實現。Regex模式被編譯成一系列的位元組碼,然後由用 C 編寫的匹配引擎執行。

生活中處處都是正則:

    比如我們描述:4條腿

      你可能會想到的是四條腿的動物或者桌子,椅子等

    繼續描述:4條腿,活的

          就只剩下四條腿的動物這一類了

二:常用匹配模式(元字元)

http://blog.csdn.net/yufenghyc/article/details/51078107

# =================================匹配模式=================================#一對一的匹配# ‘hello‘.replace(old,new)# ‘hello‘.find(‘pattern‘)#正則匹配import re#\w與\Wprint(re.findall(‘\w‘,‘hello egon 123‘)) #[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘e‘, ‘g‘, ‘o‘, ‘n‘, ‘1‘, ‘2‘, ‘3‘]print(re.findall(‘\W‘,‘hello egon 123‘)) #[‘ ‘, ‘ ‘]#\s與\Sprint(re.findall(‘\s‘,‘hello  egon  123‘)) #[‘ ‘, ‘ ‘, ‘ ‘, ‘ ‘]print(re.findall(‘\S‘,‘hello  egon  123‘)) #[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘e‘, ‘g‘, ‘o‘, ‘n‘, ‘1‘, ‘2‘, ‘3‘]#\n \t都是空,都可以被\s匹配print(re.findall(‘\s‘,‘hello \n egon \t 123‘)) #[‘ ‘, ‘\n‘, ‘ ‘, ‘ ‘, ‘\t‘, ‘ ‘]#\n與\tprint(re.findall(r‘\n‘,‘hello egon \n123‘)) #[‘\n‘]print(re.findall(r‘\t‘,‘hello egon\t123‘)) #[‘\n‘]#\d與\Dprint(re.findall(‘\d‘,‘hello egon 123‘)) #[‘1‘, ‘2‘, ‘3‘]print(re.findall(‘\D‘,‘hello egon 123‘)) #[‘h‘, ‘e‘, ‘l‘, ‘l‘, ‘o‘, ‘ ‘, ‘e‘, ‘g‘, ‘o‘, ‘n‘, ‘ ‘]#\A與\Zprint(re.findall(‘\Ahe‘,‘hello egon 123‘)) #[‘he‘],\A==>^print(re.findall(‘123\Z‘,‘hello egon 123‘)) #[‘he‘],\Z==>$#^與$print(re.findall(‘^h‘,‘hello egon 123‘)) #[‘h‘]print(re.findall(‘3$‘,‘hello egon 123‘)) #[‘3‘]# 重複匹配:| . | * | ? | .* | .*? | + | {n,m} |#.print(re.findall(‘a.b‘,‘a1b‘)) #[‘a1b‘]print(re.findall(‘a.b‘,‘a1b a*b a b aaab‘)) #[‘a1b‘, ‘a*b‘, ‘a b‘, ‘aab‘]print(re.findall(‘a.b‘,‘a\nb‘)) #[]print(re.findall(‘a.b‘,‘a\nb‘,re.S)) #[‘a\nb‘]print(re.findall(‘a.b‘,‘a\nb‘,re.DOTALL)) #[‘a\nb‘]同上一條意思一樣#*print(re.findall(‘ab*‘,‘bbbbbbb‘)) #[]print(re.findall(‘ab*‘,‘a‘)) #[‘a‘]print(re.findall(‘ab*‘,‘abbbb‘)) #[‘abbbb‘]#?print(re.findall(‘ab?‘,‘a‘)) #[‘a‘]print(re.findall(‘ab?‘,‘abbb‘)) #[‘ab‘]#匹配所有包含小數在內的數字print(re.findall(‘\d+\.?\d*‘,"asdfasdf123as1.13dfa12adsf1asdf3")) #[‘123‘, ‘1.13‘, ‘12‘, ‘1‘, ‘3‘]#.*預設為貪婪匹配print(re.findall(‘a.*b‘,‘a1b22222222b‘)) #[‘a1b22222222b‘]#.*?為非貪婪匹配:推薦使用print(re.findall(‘a.*?b‘,‘a1b22222222b‘)) #[‘a1b‘]#+print(re.findall(‘ab+‘,‘a‘)) #[]print(re.findall(‘ab+‘,‘abbb‘)) #[‘abbb‘]#{n,m}print(re.findall(‘ab{2}‘,‘abbb‘)) #[‘abb‘]print(re.findall(‘ab{2,4}‘,‘abbb‘)) #[‘abb‘]print(re.findall(‘ab{1,}‘,‘abbb‘)) #‘ab{1,}‘ ===> ‘ab+‘print(re.findall(‘ab{0,}‘,‘abbb‘)) #‘ab{0,}‘ ===> ‘ab*‘#[]print(re.findall(‘a[1*-]b‘,‘a1b a*b a-b‘)) #[]內的都為一般字元了,且如果-沒有被轉意的話,應該放到[]的開頭或結尾print(re.findall(‘a[^1*-]b‘,‘a1b a*b a-b a=b‘)) #[]內的^代表的意思是取反,所以結果為[‘a=b‘]print(re.findall(‘a[0-9]b‘,‘a1b a*b a-b a=b‘)) #[]內的^代表的意思是取反,所以結果為[‘a=b‘]print(re.findall(‘a[a-z]b‘,‘a1b a*b a-b a=b aeb‘)) #[]內的^代表的意思是取反,所以結果為[‘a=b‘]print(re.findall(‘a[a-zA-Z]b‘,‘a1b a*b a-b a=b aeb aEb‘)) #[]內的^代表的意思是取反,所以結果為[‘a=b‘]#\# print(re.findall(‘a\\c‘,‘a\c‘)) #對於正則來說a\\c確實可以匹配到a\c,但是在python解譯器讀取a\\c時,會發生轉義,然後交給re去執行,所以拋出異常print(re.findall(r‘a\\c‘,‘a\c‘)) #r代表告訴解譯器使用rawstring,即原生字串,把我們正則內的所有符號都當一般字元處理,不要轉義print(re.findall(‘a\\\\c‘,‘a\c‘)) #同上面的意思一樣,和上面的結果一樣都是[‘a\\c‘]#():分組print(re.findall(‘ab+‘,‘ababab123‘)) #[‘ab‘, ‘ab‘, ‘ab‘]print(re.findall(‘(ab)+123‘,‘ababab123‘)) #[‘ab‘],匹配到末尾的ab123中的abprint(re.findall(‘(?:ab)+123‘,‘ababab123‘)) #findall的結果不是匹配的全部內容,而是組內的內容,?:可以讓結果為匹配的全部內容print(re.findall(‘href="(.*?)"‘,‘<a href="http://www.baidu.com">點擊</a>‘))#[‘http://www.baidu.com‘]print(re.findall(‘href="(?:.*?)"‘,‘<a href="http://www.baidu.com">點擊</a>‘))#[‘href="http://www.baidu.com"‘]#|print(re.findall(‘compan(?:y|ies)‘,‘Too many companies have gone bankrupt, and the next one is my company‘))

 

# ===========================re模組提供的方法介紹===========================import re#1print(re.findall(‘e‘,‘alex make love‘) )   #[‘e‘, ‘e‘, ‘e‘],返回所有滿足匹配條件的結果,放在列表裡#2print(re.search(‘e‘,‘alex make love‘).group()) #e,只到找到第一個匹配然後返回一個包含匹配資訊的對象,該對象可以通過調用group()方法得到匹配的字串,如果字串沒有匹配,則返回None。#3print(re.match(‘e‘,‘alex make love‘))    #None,同search,不過在字串開始處進行匹配,完全可以用search+^代替match#4print(re.split(‘[ab]‘,‘abcd‘))     #[‘‘, ‘‘, ‘cd‘],先按‘a‘分割得到‘‘和‘bcd‘,再對‘‘和‘bcd‘分別按‘b‘分割#5print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘)) #===> Alex mAke love,不指定n,預設替換所有print(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘,1)) #===> Alex make loveprint(‘===>‘,re.sub(‘a‘,‘A‘,‘alex make love‘,2)) #===> Alex mAke loveprint(‘===>‘,re.sub(‘^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$‘,r‘\5\2\3\4\1‘,‘alex make love‘)) #===> love make alexprint(‘===>‘,re.subn(‘a‘,‘A‘,‘alex make love‘)) #===> (‘Alex mAke love‘, 2),結果帶有總共替換的個數#6obj=re.compile(‘\d{2}‘)print(obj.search(‘abc123eeee‘).group()) #12print(obj.findall(‘abc123eeee‘)) #[‘12‘],重用了obj
import reprint(re.findall("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>")) #[‘h1‘]print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").group()) #<h1>hello</h1>print(re.search("<(?P<tag_name>\w+)>\w+</(?P=tag_name)>","<h1>hello</h1>").groupdict()) #<h1>hello</h1>print(re.search(r"<(\w+)>\w+</(\w+)>","<h1>hello</h1>").group())print(re.search(r"<(\w+)>\w+</\1>","<h1>hello</h1>").group())
import reprint(re.findall(r‘-?\d+\.?\d*‘,"1-12*(60+(-40.35/5)-(-4*3))")) #找出所有數字[‘1‘, ‘-12‘, ‘60‘, ‘-40.35‘, ‘5‘, ‘-4‘, ‘3‘]#使用|,先匹配的先生效,|左邊是匹配小數,而findall最終結果是查看分組,所有即使匹配成功小數也不會存入結果#而不是小數時,就去匹配(-?\d+),匹配到的自然就是,非小數的數,在此處即整數print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整數[‘1‘, ‘-2‘, ‘60‘, ‘‘, ‘5‘, ‘-4‘, ‘3‘]
#計算機作業參考:http://www.cnblogs.com/wupeiqi/articles/4949995.htmlexpression=‘1-2*((60+2*(-3-40.0/5)*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))‘content=re.search(‘\(([\-\+\*\/]*\d+\.?\d*)+\)‘,expression).group() #(-3-40.0/5)
#為何同樣的運算式search與findall卻有不同結果:print(re.search(‘\(([\+\-\*\/]*\d+\.?\d*)+\)‘,"1-12*(60+(-40.35/5)-(-4*3))").group()) #(-40.35/5)print(re.findall(‘\(([\+\-\*\/]*\d+\.?\d*)+\)‘,"1-12*(60+(-40.35/5)-(-4*3))")) #[‘/5‘, ‘*3‘]#看這個例子:(\d)+相當於(\d)(\d)(\d)(\d)...,是一系列分組print(re.search(‘(\d)+‘,‘123‘).group()) #group的作用是將所有組拼接到一起顯示出來print(re.findall(‘(\d)+‘,‘123‘)) #findall結果是組內的結果,且是最後一個組的結果
#_*_coding:utf-8_*___author__ = ‘Linhaifeng‘#線上調試工具:tool.oschina.net/regex/#import res=‘‘‘http://www.baidu.com[email protected]你好010-3141‘‘‘#最常規匹配# content=‘Hello 123 456 World_This is a Regex Demo‘# res=re.match(‘Hello\s\d\d\d\s\d{3}\s\w{10}.*Demo‘,content)# print(res)# print(res.group())# print(res.span())#泛匹配# content=‘Hello 123 456 World_This is a Regex Demo‘# res=re.match(‘^Hello.*Demo‘,content)# print(res.group())#匹配目標,獲得指定資料# content=‘Hello 123 456 World_This is a Regex Demo‘# res=re.match(‘^Hello\s(\d+)\s(\d+)\s.*Demo‘,content)# print(res.group()) #取所有匹配的內容# print(res.group(1)) #取匹配的第一個括弧內的內容# print(res.group(2)) #去陪陪的第二個括弧內的內容#貪婪匹配:.*代表匹配儘可能多的字元# import re# content=‘Hello 123 456 World_This is a Regex Demo‘## res=re.match(‘^He.*(\d+).*Demo$‘,content)# print(res.group(1)) #只列印6,因為.*會儘可能多的匹配,然後後面跟至少一個數字#非貪婪匹配:?匹配儘可能少的字元# import re# content=‘Hello 123 456 World_This is a Regex Demo‘## res=re.match(‘^He.*?(\d+).*Demo$‘,content)# print(res.group(1)) #只列印6,因為.*會儘可能多的匹配,然後後面跟至少一個數字#匹配模式:.不能匹配分行符號content=‘‘‘Hello 123456 World_Thisis a Regex Demo‘‘‘# res=re.match(‘He.*?(\d+).*?Demo$‘,content)# print(res) #輸出None# res=re.match(‘He.*?(\d+).*?Demo$‘,content,re.S) #re.S讓.可以匹配分行符號# print(res)# print(res.group(1))#轉義:# content=‘price is $5.00‘# res=re.match(‘price is $5.00‘,content)# print(res)## res=re.match(‘price is \$5\.00‘,content)# print(res)#總結:盡量精簡,詳細的如下    # 盡量使用泛匹配模式.*    # 盡量使用非貪婪模式:.*?    # 使用括弧得到匹配目標:用group(n)去取得結果    # 有分行符號就用re.S:修改模式#re.search:會掃描整個字串,不會從頭開始,找到第一個匹配的結果就會返回# import re# content=‘Extra strings Hello 123 456 World_This is a Regex Demo Extra strings‘## res=re.match(‘Hello.*?(\d+).*?Demo‘,content)# print(res) #輸出結果為None## import re# content=‘Extra strings Hello 123 456 World_This is a Regex Demo Extra strings‘## res=re.search(‘Hello.*?(\d+).*?Demo‘,content) ## print(res.group(1)) #輸出結果為#re.search:只要一個結果,匹配演練,import recontent=‘‘‘<tbody><tr id="4766303201494371851675" class="even "><td><div class="hd"><span class="num">1</span><div class="rk "><span class="u-icn u-icn-75"></span></div></div></td><td class="rank"><div class="f-cb"><div class="tt"><a href="/song?id=476630320"><img class="rpic" src="http://p1.music.126.net/Wl7T1LBRhZFg0O26nnR2iQ==/19217264230385030.jpg?param=50y50&amp;quality=100"></a><span data-res-id="476630320" "# res=re.search(‘<a\shref=.*?<b\stitle="(.*?)".*?b>‘,content)# print(res.group(1))#re.findall:找到合格所有結果# res=re.findall(‘<a\shref=.*?<b\stitle="(.*?)".*?b>‘,content)# for i in res:#     print(i)#re.sub:字串替換import recontent=‘Extra strings Hello 123 456 World_This is a Regex Demo Extra strings‘# content=re.sub(‘\d+‘,‘‘,content)# print(content)#用\1取得第一個括弧的內容#用法:將123與456換位置# import re# content=‘Extra strings Hello 123 456 World_This is a Regex Demo Extra strings‘## # content=re.sub(‘(Extra.*?)(\d+)(\s)(\d+)(.*?strings)‘,r‘\1\4\3\2\5‘,content)# content=re.sub(‘(\d+)(\s)(\d+)‘,r‘\3\2\1‘,content)# print(content)# import re# content=‘Extra strings Hello 123 456 World_This is a Regex Demo Extra strings‘## res=re.search(‘Extra.*?(\d+).*strings‘,content)# print(res.group(1))# import requests,re# respone=requests.get(‘https://book.douban.com/‘).text# print(respone)# print(‘======‘*1000)# print(‘======‘*1000)# print(‘======‘*1000)# print(‘======‘*1000)# res=re.findall(‘<li.*?cover.*?href="(.*?)".*?title="(.*?)">.*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span.*?</li>‘,respone,re.S)# # res=re.findall(‘<li.*?cover.*?href="(.*?)".*?more-meta.*?author">(.*?)</span.*?year">(.*?)</span.*?publisher">(.*?)</span>.*?</li>‘,respone,re.S)### for i in res:#     print(‘%s    %s    %s   %s‘ %(i[0].strip(),i[1].strip(),i[2].strip(),i[3].strip()))

python正則表達

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.