python使用正則來處理各種匹配問題
更新時間:2019年12月22日 11:47:55 作者:D_dalei
這篇文章主要介紹了python使用正則來處理各種匹配問題,本文通過實例代碼給大家講解的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下
正則表達式是一個特殊的字符序列,它能幫助你方便的檢查一個字符串是否與某種模式匹配。本文給大家介紹python使用正則來處理各種匹配問題,具體代碼如下所述:
import re
##匹配列表內(nèi)的非負整數(shù)
list = [99,100,-100,-1,90]
pattern = re.compile(r'[1-9]\d*|0')
for i in list:
m = pattern.search(str(i))
print(m)
##匹配列表內(nèi)的整數(shù)
list = [99,100,-100,-1,90]
pattern = re.compile(r'[1-9]\d*')
for i in list:
m = pattern.match(str(i))
print(m)
##匹配列表內(nèi)的非正整數(shù)
list = [99,100,-100,-1,90]
pattern = re.compile(r'-[1-9]\d*|0')
for i in list:
m = pattern.match(str(i))
print(m)
# ##正則匹配郵箱
c = re.compile(r'^\w+@(\w+\.)+(com|cn|net|edu)$')
string = '50772618@qq.com'
s = c.search(string)
if s:
print(s.group())
##匹配十一位手機號
c = re.compile(r'^1[3-9]\d{9}$')
s = c.search('18785397892')
if s:
print(s.group())
c = re.compile(r'^[1-9]\d*|0$')
s = c.search('')
if s:
print(s.group())
##正則匹配日期
pattern = re.compile(r'[1-9]\d{3}-(1[0-2]|0?[1-9])-(3[0-1]|[1-2]\d|0?[1-9])')#定義匹配模式
string = 'hgfdjyjhfdjjj,2019-12-19jhgfjhgfjhf'
s = re.search(string)
print(s.group())
print(pattern.search(string,s.end()+1))
##匹配密碼
pattern = re.compile(r'[A-Z]\w{7,9}')
m = pattern.search('basldaE3217894_324yiudasjl')
if m :
print(m.group())
總結(jié)
以上所述是小編給大家介紹的python使用正則來處理各種匹配問題,希望對大家有所幫助!
相關(guān)文章
Python實現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法示例
這篇文章主要介紹了Python實現(xiàn)讀取txt文件并轉(zhuǎn)換為excel的方法,涉及Python針對txt文件的讀取及Excel格式文件生成相關(guān)操作技巧,需要的朋友可以參考下2018-05-05
Pandas時間序列基礎(chǔ)詳解(轉(zhuǎn)換,索引,切片)
今天小編就為大家分享一篇Pandas時間序列基礎(chǔ)詳解(轉(zhuǎn)換,索引,切片),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02

