十三 re模塊

一:什么是正則?

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

生活中處處都是正則:

? ? 比如我們描述:4條腿

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

? ? 繼續描述:4條腿,活的

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

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

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

# =================================匹配模式=================================
#一對一的匹配
# 'hello'.replace(old,new)
# 'hello'.find('pattern')#正則匹配
import re
#\w與\W
print(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與\S
print(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與\t
print(re.findall(r'\n','hello egon \n123')) #['\n']
print(re.findall(r'\t','hello egon\t123')) #['\n']#\d與\D
print(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與\Z
print(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中的ab
print(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
#1
print(re.findall('e','alex make love') )   #['e', 'e', 'e'],返回所有滿足匹配條件的結果,放在列表里
#2
print(re.search('e','alex make love').group()) #e,只到找到第一個匹配然后返回一個包含匹配信息的對象,該對象可以通過調用group()方法得到匹配的字符串,如果字符串沒有匹配,則返回None。#3
print(re.match('e','alex make love'))    #None,同search,不過在字符串開始處進行匹配,完全可以用search+^代替match#4
print(re.split('[ab]','abcd'))     #['', '', 'cd'],先按'a'分割得到''和'bcd',再對''和'bcd'分別按'b'分割#5
print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默認替換所有
print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
print('===>',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),結果帶有總共替換的個數#6
obj=re.compile('\d{2}')print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj

import re
print(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 re

#使用|,先匹配的先生效,|左邊是匹配小數,而findall最終結果是查看分組,所有即使匹配成功小數也不會存入結果
#而不是小數時,就去匹配(-?\d+),匹配到的自然就是,非小數的數,在此處即整數
#
print(re.findall(r"-?\d+\.\d*|(-?\d+)","1-2*(60+(-40.35/5)-(-4*3))")) #找出所有整數['1', '-2', '60', '', '5', '-4', '3']

#找到所有數字:
print(re.findall('\D?(\-?\d+\.?\d*)',"1-2*(60+(-40.35/5)-(-4*3))")) # ['1','2','60','-40.35','5','-4','3']

#計算器作業參考:http://www.cnblogs.com/wupeiqi/articles/4949995.html
expression='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結果是組內的結果,且是最后一個組的結果

search與findall

?

#_*_coding:utf-8_*_
__author__ = 'Linhaifeng'
#在線調試工具:tool.oschina.net/regex/#
import re

s='''
http://www.baidu.com
egon@oldboyedu.com
你好
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_This
is 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 re
content='''
<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 re
content='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()))

轉載于:https://www.cnblogs.com/xuxuchao/p/10244488.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/248674.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/248674.shtml
英文地址,請注明出處:http://en.pswp.cn/news/248674.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

帶你玩轉 ui 框架 ——scoped及樣式穿透問題詳解

前言 在我們前端的開發中經常會使用到各種 ui 框架 下面這兩個是比較火的&#xff0c;也是我常用的兩個ui框架。 問題描述 但是在使用框架的時候難免會遇到需要改變組件中的一些樣式&#xff0c;當然如果我們所有頁面的組件樣式都是統一的話&#xff0c;我們可以進行全局設置…

Npoi Web 項目中(XSSFWorkbook) 導出出現無法訪問已關閉的流

NPOI生產.xlsx文件件時&#xff0c;在使用book.Write(ms);后&#xff0c;會關閉流&#xff0c;這樣導致再次使用Respons輸出流的時候就出錯了。 造成關閉流的主要原因有時其實是跨域&#xff0c;同域是沒有問題的。 //新建類 重寫Npoi流方法 public class NpoiMemoryStream : M…

三分鐘帶你掌握 CSS3 的新屬性

文章目錄1. css3簡介2. css3邊框2.1 邊框圓角2.2 邊框陰影3. css3背景3.1背景圖大小3.2背景圖起始點4. css3文本效果4.1 文本陰影4.2 文本換行5. css3字體圖標6. css32D轉換7. css3 3D轉換8. css3 transition8.1 單項改變8.2 單項改多項改變9. css3 動畫1. css3簡介 CSS 用于控…

用 div 仿寫 input 和 textarea 功能

div仿寫input和textarea input不能換行&#xff0c;textarea也不能跟隨內容多少而增加高度。 contenteditable true; <div class"msg_content" contenteditable"true" placeholder在這里輸入您的留言或建議></div> .msg_content {box-sizing:…

Vue項目中如何設置動態的TDK

TDK是什么 TDK就是網站的標題&#xff08;title&#xff09;、描述&#xff08;description&#xff09;和關鍵詞&#xff08;keyword&#xff09; TDK在哪里 上面大佬對TDK的概念解釋的很全面&#xff0c;但是在網頁中的TDK在哪里呢&#xff0c;作為開發人員打開F12我們就…

[Pytorch]Pytorch的tensor變量類型轉換

原文&#xff1a;https://blog.csdn.net/hustchenze/article/details/79154139 Pytorch的數據類型為各式各樣的Tensor,Tensor可以理解為高維矩陣。與Numpy中的Array類似。Pytorch中的tensor又包括CPU上的數據類型和GPU上的數據類型&#xff0c;一般GPU上的Tensor是CPU上的Tenso…

PHP從零開始--基礎篇

一、 變量 1.1概念 變量是存儲數據的用的容器。 1.2定義變量 變量名的語法規則&#xff1a; 可以是數字、字母、下劃線&#xff0c;但是不能以數字開頭不能出現空格變量名是區分大小寫變量名不能是系統中的關鍵字行業約定的語法規范 駝峰命名法 比如 myname 定義成 myNam…

node

? Table of Contents 1. 全局對象2. 代碼執行優先級3. 模塊導入4. 模塊加載 4.1. 文件模塊優先級4.2. 文件夾加載優先級 4.2.1. 包&#xff08;文件夾&#xff09;下的入口文件優先級4.2.2. 包加載優先級5. 核心模塊的簡單使用 5.1. events1 全局對象 globalconsole.log(globa…

一個關于WCF調用遠程鏈接返回405錯誤不允許使用此方法的問題

最近在調試WCF的接口時一直返回“405不允許使用此方法”&#xff0c;這個問題困擾了大半天&#xff0c;網上查了各種辦法&#xff0c;但是每個人遇到的問題不同還是不能解決。 最后無意之中發現問題所在&#xff0c;記錄一下幫助后面的同學解決問題。 WCF遠程方法會配置屬性Web…

PHP從零開始--循環數組

一、循環 1.1單層for循環 1.1.1基礎語法 for(初識變量;結束范圍;累加/累減){ 重復執行的代碼 } 1、 先初識化變量$i 2、 $i<100表達式進行判斷 3、 跳入循環&#xff0c;執行重復代碼 4、 累加或者累加 5、 再進行$i<100表達式判斷 6、 再跳入循環&#xff0c;執行重復…

Spring Cloud(F版)搭建高可用服務注冊中心

上一篇文章【Spring Cloud搭建注冊中心】成功搭建了一個Eureka Server服務注冊中心&#xff0c;不過相信細心的朋友都會發現&#xff0c;這個服務注冊中心是一個單節點服務注冊中心&#xff0c;萬一發生故障或者服務器宕機&#xff0c;那所有的服務可就不能使用了&#xff0c;這…

Python(60)_閉包

1 、閉包的概念 #-*-coding:utf-8-*- 1、閉包&#xff1a;內部函數調用外部函數的變量def outer():a 1def inner():print(a)print(inner.__closure__) outer() print(outer.__closure__) 2 閉包的使用 #-*-coding:utf-8-*- 1、閉包&#xff1a;內部函數調用外部函數的變量 …

PHP從零開始--錯誤處理函數

一、錯誤處理 1.1錯誤種類 1.1.1Notices 比如沒有定義變量確使用了會報notice錯誤&#xff0c;只是提醒注意&#xff0c;不影響后續代碼執行 1.1.2Warnings 這是警告錯誤&#xff0c;比如include引入一個并不存在的文件&#xff0c;不影響后續代碼執行 1.1.3Fatal Erro…

第四單元博客總結——暨OO課程總結

第四單元博客總結——暨OO課程總結 第四單元架構設計 第一次UML作業 簡單陳述 第一次作業較為簡單&#xff0c;只需要實現查詢功能&#xff0c;并在查詢的同時考慮到性能問題&#xff0c;即我簡單的將每一次查詢的結果以及遞歸的上層結果都存儲下來&#xff0c;使用一個Boolean…

兩列布局:6種方法

面試過程中總會文檔兩列布局&#xff0c;左邊等寬&#xff0c;右邊自適應幾種方法&#xff1f;以下提供6種為君解憂 <div id"wrap"><div id"left"></div><div id"right"></div> </div>需求就是左側定寬&…

PHP從零開始--數據庫

文章目錄一、 數據庫簡介1.1概念1.2命令行操作1.3連接數據庫1.4配置環境變量二、 數據庫的相關操作2.1顯示所有倉庫2.2創建倉庫2.3刪除倉庫2.4切換倉庫三、 數據表的相關操作3.1概念3.2顯示所有的數據表3.3創建數據表3.2修改字段名3.3查看表結構3.4添加字段3.5刪除字段3.6更改數…

常用SQL語句

將記錄的某一字段值設置為空&#xff08;null&#xff09;UPDATE 表名 SET 字段名NULL WHERE 條件字段名123; 更新整列為某個值UPDATE 表名 SET 字段名NULL 轉載于:https://www.cnblogs.com/zhcBlog/p/10254066.html

如何下載js類庫

https://bower.io/ 這個已經淘汰 https://learn.jquery.com/jquery-ui/environments/bower/ Web sites are made of lots of things — frameworks, libraries, assets, and utilities. Bower manages all these things for you. Keeping track of all these packages and mak…

Python 常用系統模塊整理

Python中的常用的系統模塊中部分函數等的整理 random: 隨機數sys: 系統相關os: 系統相關的subprocess: 執行新的進程multiprocessing: 進程相關threading: 線程相關pickle: 將對象轉換成二進制文件time: 時間datetime: 基本的日期和時間類型timeit: 準確測量小段代碼的執行時間…

PHP從零開始--字段修飾符數據操作SQL語言

文章目錄一、 字段修飾符1.1主鍵1.2自動增長1.3非空1.4默認值1.5外鍵二、 對數據的操作2.1增加數據2.2刪除數據2.3更新數據2.4查詢數據2.4.1查詢所有的數據2.4.2查詢指定字段2.4.3去除重復字段2.4.4where表達式詳解2.4.5分組查詢2.4.6排序三、 SQL語言3.1DML3.2DDL3.3DCL一、 字…