本篇文章給大家分享的是有關什么是Python正則表達式,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
創新互聯公司主營巴州網站建設的網絡公司,主營網站建設方案,app軟件開發,巴州h5微信小程序定制開發搭建,巴州網站營銷推廣歡迎巴州等地區企業咨詢
1、查找第一個匹配串
s = 'i love python very much'
pat = 'python'
r = re.search(pat,s)
print(r.span()) #(7,13)
2、查找所有1
s = '山東省濰坊市青州第1中學高三1班'
pat = '1'
r = re.finditer(pat,s)
for i in r:
print(i)
# <re.Match object; span=(9, 10), match='1'>
# <re.Match object; span=(14, 15), match='1'>
3、\d匹配數字[0-9]
s = '一共20行代碼運行時間13.59s'
pat = r'\d+' # +表示匹配數字(\d表示數字的通用字符)1次或多次
r = re.findall(pat,s)
print(r)
# ['20', '13', '59']
4、表示前一個字符匹配0或1次
s = '一共20行代碼運行時間13.59s'
pat = r'\d+\.?\d+' # ?表示匹配小數點(\.)0次或1次
r = re.findall(pat,s)
print(r)
# ['20', '13.59']
5、^匹配字符串的開頭
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'^[emrt]' #查找以
r = re.findall(pat,s)
print(r)
# [],因為字符串的開頭是字符`T`,不在emrt匹配范圍內,所以返回為空
6、re.I忽略大小寫
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'^[emrt]' #查找以
r = re.compile(pat,re.I).search(s)
print(r)
# <re.Match object; span=(0, 1), match='T'>表明字符串的開頭在匹配列表中
7、使用正則提取單詞
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s[a-zA-Z]+'
r = re.findall(pat,s)
print(r) #[' module', ' provides', ' regular', ' expression', ' matching', ' operations', ' similar', ' to', ' those', ' found', ' in', ' Perl']
8、只捕獲單詞,去掉空格
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s([a-zA-Z]+)'
r = re.findall(pat,s)
print(r) #['module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']
9、補充上第一個單詞
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s?([a-zA-Z]+)'
r = re.findall(pat,s)
print(r) #['This', 'module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']
10、使用split函數直接分割單詞
使用以上方法分割單詞,不是簡潔的,僅僅為了演示。分割單詞最簡單還是使用 split函數。
s = 'This module provides regular expression matching operations similar to those found in Perl'
pat = r'\s+'
r = re.split(pat,s)
print(r) # ['This', 'module', 'provides', 'regular', 'expression', 'matching', 'operations', 'similar', 'to', 'those', 'found', 'in', 'Perl']
以上就是什么是Python正則表達式,小編相信有部分知識點可能是我們日常工作會見到或用到的。希望你能通過這篇文章學到更多知識。更多詳情敬請關注創新互聯行業資訊頻道。
網頁標題:什么是Python正則表達式
文章出自:http://m.newbst.com/article42/pjdphc.html
成都網站建設公司_創新互聯,為您提供Google、域名注冊、做網站、微信公眾號、網站收錄、云服務器
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯