新聞中心
大概在十幾年前,自動(dòng)車還是大家比較流行的出門工具。后來(lái)人們覺得騎到很遠(yuǎn)的地方比較費(fèi)勁,給自行車加上了電瓶,這就成了當(dāng)時(shí)簡(jiǎn)易的電動(dòng)車版本。同樣的在python3的re模塊中,正則表達(dá)式經(jīng)常和re放在一起使用,小編認(rèn)為兩者的關(guān)系就類似于自動(dòng)車和電瓶的組裝,大家覺得呢?下面就講講結(jié)合在一起怎么使用吧。

成都創(chuàng)新互聯(lián)公司堅(jiān)持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)、外貿(mào)營(yíng)銷網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時(shí)代的哈巴河網(wǎng)站設(shè)計(jì)、移動(dòng)媒體設(shè)計(jì)的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
# 推薦使用 Python 正則表達(dá)式的幾個(gè)步驟 import re regex = re.compile(r'正則表達(dá)式') # 創(chuàng)建一個(gè) Regex 對(duì)象,使用 r'' 原始字符串不需要轉(zhuǎn)義 regex.match() # regex.search() # 返回一個(gè) Match 對(duì)象,包含被查找字符串中的第一次被匹配的文本 regex.findall() # 返回一組字符串列表,包含被查找字符串中的所有匹配 regex.sub() # 替換字符串,接收兩個(gè)參數(shù),新字符串和正則表達(dá)式 ...
簡(jiǎn)單示例:
>>> import re
>>> regex = re.compile(r'\b\w{6}\b') # 匹配6個(gè)字符的單詞
>>> regex.search('My phone number is 421-2343-121')
>>> text = regex.search('My phone number is 421-2343-121')
>>> text.group() # 調(diào)用 group() 返回結(jié)果
'number'
>>> regex = re.compile(r'0\d{2}-\d{8}|0\d{3}-\d{7}') # 注意分枝條件的使用
>>> text = regex.search('My phone number is 021-76483929')
>>> text.group()
'021-76483929'
>>> text = regex.search('My phone number is 0132-2384753')
>>> text.group()
'0132-2384753'
>>> regex = re.compile(r'(0\d{2})-(\d{8})') # 括號(hào)分組的使用
>>> text = regex.search('My phone number is 032-23847533')
>>> text.group(0)
'032-23847533'
>>> text.group(1)
'032'
>>> text.group(2)
'23847533'
>>> regex = re.compile(r'(0\d{2}-)?(\d{8})') # ?之前的分組表示是可選的分組,如果需要匹配真正的?,就使用轉(zhuǎn)義字符\?
>>> text = regex.search('My phone number is 032-23847533')
>>> text.group()
'032-23847533'
>>> text = regex.search('My phone number is 23847533')
>>> text.group()
'23847533'
>>> regex = re.compile(r'(Py){3,5}') # Python 默認(rèn)是貪心,盡可能匹配最長(zhǎng)的字符串
>>> text = regex.search('PyPyPyPyPy')
>>> text.group()
'PyPyPyPyPy'
>>> regex = re.compile(r'(Py){3,5}?') # ? 聲明非貪心,盡可能匹配最短的字符串
>>> text = regex.search('PyPyPyPyPy')
>>> text.group()
'PyPyPy'
其它正則規(guī)則可自行測(cè)試。下面是 Python 正則表達(dá)式的常用方法:
# 這里測(cè)試 findall() 以及 sub()
# findall()
>>> regex = re.compile(r'0\d{2}-\d{8}|0\d{3}-\d{7}')
>>> regex.findall('Cell: 021-38294729, Work: 0413-3243243')
['021-38294729', '0413-3243243']
>>> regex = re.compile(r'Hello \w+')
>>> regex.sub('Hello Python', 'falkdjfsk Hello c sldfjlksdj Hello java sdfsj')
'falkdjfsk Hello Python sldfjlksdj Hello Python sdfsj'
相信通過(guò)以上的三段代碼,小伙伴們已經(jīng)初步體會(huì)re結(jié)合正則表達(dá)式的運(yùn)用了,看不懂的小伙伴多試幾遍哦~更多Python學(xué)習(xí)推薦:PyThon學(xué)習(xí)網(wǎng)教學(xué)中心。
文章名稱:創(chuàng)新互聯(lián)Python教程:python3re結(jié)合正則表達(dá)式如何使用?
分享網(wǎng)址:http://www.5511xx.com/article/cdcjpsg.html


咨詢
建站咨詢
