本篇文章帶給大家的內容是關於Python正規表示式和re庫的相關內容介紹(程式碼範例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。
正規表示式是定義搜尋模式的字元序列。通常這種模式被字串搜尋演算法用於字串上的「查找」或「尋找和取代」操作,或用於輸入驗證。
1. 正規表示式的語法
#. 表示任何單一字元
- ##[]字元集,對單一字元給出取值範圍
- [^] 非字元集,對單一字元給出排除範圍
- *前一個字元0次或無限次擴展
- 前一個字元1次或無限次擴充
- ?前一個字元0次或1次擴展
- |左右表達式任一
- #{m}擴充前一個字元m次
- #{m,n}擴展前一個字元m至n次
- ^匹配字串開頭 ##$符合字串結尾
- ()分組標記,內部只能使用|運算子
- d數字,等價於[0-9]
- w單字字符,等價於[A-Z,a-z,0-9]
Re函式庫是python的標準函式庫,主要用於字串匹配,呼叫方法:import re
2.1. 正規表示式字串的型別
re函式庫採用raw string類型來表示正規表示式,表示為
r'text'
#raw string是不包含對轉義符的再次轉義的字串,總而言就是string會對字元轉義,而raw string不會,因為在正規表示中會出現轉義符號,所以避免繁瑣我們使用raw string
2.2. Re函式庫主要功能函數
- #re.search
()在一個字串中搜尋正規表示式的第一個位置,傳回match物件
- #re .match()
從字串的起始位置起符合正規表示式,傳回match物件
- re.findall()
搜尋字串,以清單類型傳回全部能符合的子字串
- re.split()
將一個字串依照正規表示式符合結果分割,傳回清單類型
- re.finditer()
搜尋字串,傳回一個符合結果的迭代類型,每個迭代元素是match物件
- re.sub()
在一個字串中取代所有符合正規表示式的子字串,並傳回替換後的字串
2.2.1 . re.search(pattern, string, flags=0)
在一個字串中搜尋正規表示式的第一個位置,傳回match物件
- pattern : 正規表示式的字串或原生字串表示
- string : 待匹配字串
- flags : 正規表示式使用時的控制標記
- re.I re.IGNORECASE 忽略正規表示式的大小寫,[A‐Z]能夠匹配小寫字元
- re .M re.MULTILINE 正規表示式中的^運算子能夠將給定字串的每行當作匹配開始
- re.S re.DOTALL 正規表示式中的.操作符能夠匹配所有字符,預設匹配除換行外的所有字符
- 舉例說明:
import re match = re.search(r'[1-9]\d{5}', 'BIT 100081') if match: print(match.group(0)) 结果为100081
2.2.2. re.match(pattern, string, flags= 0)
從字串的起始位置起符合正規表示式,傳回match物件
參數同search函數範例說明:
import re match = re.match(r'[1-9]\d{5}', 'BIT 100081') print(match.group(0)) 结果会报错,match为空,因为match函数是 从字符串开始位置开始匹配,因为从开始位置没有匹配到,所以为空
2.2.3. re. findall(pattern, string, flags=0)
搜尋字串,以清單類型傳回全部能符合的子字串
參數同search範例說明:
import re ls=re.findall(r'[1-9]\d{5}', 'BIT100081 TSU100084') print(ls) 结果为['100081', '100084']
2.2 .4. re.split(pattern, string, maxsplit=0, flags=0)
將一個字串依照正規表示式比對結果分割傳回清單類型
- #maxsplit : 最大分割數,剩餘部分作為最後一個元素輸出
- 舉例說明:
import re re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084') 结果['BIT', ' TSU', ' '] re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084', maxsplit=1) 结果['BIT', ' TSU100081']
2.2.5. re.finditer(pattern, string, maxsplit =0, flags=0)
搜尋字串,傳回一個符合結果的迭代類型,每個迭代元素是match物件
參數同search舉例說明:
import re for m in re.finditer(r'[1-9]\d{5}', 'BIT100081 TSU100084'): if m: print(m.group(0)) 结果为 100081 100084
2.2.6. re.sub(pattern, repl, string, count=0, flags=0)
在一個字串中替換所有符合正規表示式的子字串傳回替換後的字串
- repl : 取代符合字串的字串
- count : 符合的最大替換次數
- 舉例說明:
import re re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 TSU100084') 结果为 'BIT:zipcode TSU:zipcode'
2.3 Re函式庫的另一種等價用法(物件導向)
rst=re.search(r'[1-9]\d{5}', 'BIT 100081') 函数式的调用,一次性操作
pat=re.compile(r'[1-9]\d{5}') rst=pat.search('BIT 100081') 编译后多次操作
regex=re.complie(pattern,flags=0)
regex也有以上六種用法
2.4 Re函式庫的Match物件
Match物件是是一次符合的結果,包含符合的許多資訊
以下是Match物件的屬性
- .string 待符合的文字
- ##.re 符合時所使用的patter物件(正規表達式)
.pos 正規表示式搜尋文字的起始位置
.endpos 正規表示式搜尋文字的結束位置
以下是Match物件的方法
#.group(0) 取得符合後的字串
#.start() 匹配字串在原始字串的開始位置
.end() 匹配字串在原始字串的結束位置
.span() 傳回(.start(), .end())
#2.5 Re函式庫的貪婪匹配和最小匹配
當正規表示式可以符合長短不同的多項時,回傳哪一個呢? Re庫預設採用貪婪匹配,即傳回匹配最長的子字串
最小匹配
- ##*? 前一個字元0次或無限次擴展,最小匹配
- ? 前一個字元1次或無限次擴展,最小匹配
- ??前一個字元0次或1次擴展,最小匹配
- {m,n}? 擴展前一個字元m至n次(含n),最小匹配
只要長度輸出可能不同的,都可以透過在運算子後面增加?變成最小匹配
#
以上是Python正規表示式和re庫的相關內容介紹(程式碼範例)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

記事本++7.3.1
好用且免費的程式碼編輯器

PhpStorm Mac 版本
最新(2018.2.1 )專業的PHP整合開發工具