python中使用正則表達式的方法詳解
更新時間:2022年03月29日 17:36:58 作者:coding白
這篇文章主要為大家詳細介紹了python中使用正則表達式的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
在python中使用正則表達式,主要通過下面的幾個方法
search(pattern, string, flags=0)
- 掃描整個string并返回匹配pattern的結(jié)果(None或?qū)ο?
- 有匹配的字符串的話返回一個對象(包含符合匹配條件的第一個字符串),否則返回None
import re
#導(dǎo)入正則庫
content = 'Hello 1234567 Hello 666'
#要匹配的文本
res = 'Hello\s'
#正則字符串
result = re.search(res, content)
if result is not None:
print(result.group())
#輸出匹配得到的字符串 'hello'(返回的得是第一個'hello')
print(result.span())
#輸出輸出匹配的范圍(匹配到的字符串在原字符串中的位置的范圍)
res1 = 'Hello\s(\d)(\d+)'
result = re.search(res1, content)
print(result.group(1))
#group(1)表示匹配到的第一個組(即正則字符串中的第一個括號)的內(nèi)容
print(result.group(2))
findall(pattern, string, flags=0)
- 掃描整個context并返回匹配res的結(jié)果(None或列表)
- 有匹配的字符串的話返回一個列表(符合匹配條件的每個子字符串作為它的一個元素),否則返回None
import re
res = 'Hello\s'
results = re.findall(res, content)
if results is not None:
print(results)
#輸出: ['hello','hello']
res1 = 'Hello\s(\d)(\d+)'
results = re.findall(res1, content)
if result is not None:
print(results)
# 當(dāng)正則字符串中出現(xiàn)括號時,所得到列表的每個元素是元組
# 每個元組的元素都是依次匹配到的括號內(nèi)的表達式的結(jié)果
#輸出: [('1','1234567'),('6','666')]
sub(pattern, repl, string, count=0, flags=0)
- 可以來修改文本
- 用將用pattern匹配string所得的字符串替換成repl
import re content = '54aK54yr5oiR54ix5L2g' res = '\d+' content = re.sub(res, '', content) print(content)
compile(pattern, flags=0)
將正則表達式res編譯成一個正則對象并返回,以便復(fù)用
import re
content1 = '2019-12-15 12:00'
content2 = '2019-12-17 12:55'
content3 = '2019-12-22 13:21'
pattern = re.compile('\d{2}:\d{2}')
result1 = re.sub(pattern, '', content1)
result2 = re.sub(pattern, '', content2)
result3 = re.sub(pattern, '', content3)
print(result1, result2, result3)
flags的一些常用值
- re.I 使匹配對大小寫不敏感
- re.S 使.匹配包括換行符在內(nèi)的所有字符
import re re.compile(res, re.I) #如果res可以匹配大寫字母,那它也可以匹配相應(yīng)的小寫字母,反之也可 re.compile(res,re.S) #使res中的'.'字符可以匹配包括換行符在內(nèi)的所有字符
總結(jié)
本篇文章就到這里了,希望能夠給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!
相關(guān)文章
Pandas數(shù)據(jù)形狀df.shape的實現(xiàn)
本文主要介紹了Pandas數(shù)據(jù)形狀df.shape的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Centos 升級到python3后pip 無法使用的解決方法
今天小編就為大家分享一篇Centos 升級到python3后pip 無法使用的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
Python中__init__和__new__的區(qū)別詳解
這篇文章主要介紹了Python中__init__和__new__的區(qū)別詳解,并著重說明了__new__的作用及什么情況下使用__new__,需要的朋友可以參考下2014-07-07
django創(chuàng)建簡單的頁面響應(yīng)實例教程
這篇文章主要給大家介紹了關(guān)于django如何創(chuàng)建簡單的頁面響應(yīng)的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用django具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
python使用MySQLdb訪問mysql數(shù)據(jù)庫的方法
這篇文章主要介紹了python使用MySQLdb訪問mysql數(shù)據(jù)庫的方法,實例分析了Python使用MySQLdb模塊操作mysql數(shù)據(jù)庫的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-08-08

