溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python3 re結合正則表達式怎么用

發布時間:2020-11-21 09:30:11 來源:億速云 閱讀:188 作者:小新 欄目:編程語言

小編給大家分享一下python3 re結合正則表達式怎么用,相信大部分人都還不怎么了解,因此分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后大有收獲,下面讓我們一起去了解一下吧!

# 推薦使用 Python 正則表達式的幾個步驟
import re
regex = re.compile(r'正則表達式') # 創建一個 Regex 對象,使用 r'' 原始字符串不需要轉義
regex.match() #
regex.search() # 返回一個 Match 對象,包含被查找字符串中的第一次被匹配的文本
regex.findall() # 返回一組字符串列表,包含被查找字符串中的所有匹配
regex.sub()  # 替換字符串,接收兩個參數,新字符串和正則表達式
...

簡單示例:

>>> 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'

其它正則規則可自行測試。下面是 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'

以上是python3 re結合正則表達式怎么用的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女