新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python3re結合正則表達式如何使用?
大概在十幾年前,自動車還是大家比較流行的出門工具。后來人們覺得騎到很遠的地方比較費勁,給自行車加上了電瓶,這就成了當時簡易的電動車版本。同樣的在python3的re模塊中,正則表達式經(jīng)常和re放在一起使用,小編認為兩者的關系就類似于自動車和電瓶的組裝,大家覺得呢?下面就講講結合在一起怎么使用吧。

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


咨詢
建站咨詢
