一、Python中的正則表達式基礎
正則表達式是一種通用的文本匹配方式,可以匹配特定規則的字元串。Python內置了re模塊,可以用來處理正則表達式。
在Python中,使用正則表達式通常需要以下步驟:
- 導入re模塊,調用相應函數
- 編寫正則表達式規則
- 對目標字元串進行匹配和查找
- 使用匹配結果進行相應的處理
下面是一個簡單的示例:
import re
pattern = 'hello'
text = 'hello, world!'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
else:
print('Match not found')
以上代碼在text中查找’hello’,輸出’Match found: hello’。
二、正則表達式規則
使用正則表達式,首先需要編寫相應的規則。以下是一些常用的規則:
.
: 匹配任意字元^
: 匹配字元串的開頭$
: 匹配字元串的結尾*
: 匹配0個或多個重複字元+
: 匹配1個或多個重複字元?
: 匹配0個或1個字元{n}
: 匹配n個重複字元{n,}
: 匹配至少n個重複字元{n,m}
: 匹配n~m個重複字元(貪婪模式)[abc]
: 匹配a、b、c中任意一個字元[a-z]
: 匹配a~z中任意一個小寫字母[^0-9]
: 匹配任意一個非數字字元((a|b)c)
: 匹配ac或bc
可以將這些規則進行組合,用於匹配更複雜的字元串。下面是一個示例:
import re
pattern = '\d+' # 匹配一個或多個數字
text = 'Today is April 1st, 2022'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
else:
print('Match not found')
以上代碼在text中查找一個或多個數字,輸出’Match found: 1’。
三、Python中的正則表達式函數
Python中常用的正則表達式函數有:
re.search()
: 在字元串中查找匹配項,僅返回第一項re.findall()
: 在字元串中查找所有匹配項,返回一個列表re.sub()
: 在字元串中查找匹配項,並替換為指定字元串re.compile()
: 編譯一個正則表達式,返回一個可重用的正則表達式對象
四、正則表達式常見應用
1. 匹配郵件地址
import re
pattern = r'\w+@\w+\.\w+'
text = 'My email address is abc_123@example.com'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
else:
print('Match not found')
以上代碼在text中查找郵件地址,輸出’Match found: abc_123@example.com’。
2. 匹配HTML標籤
import re
pattern = r'(.+?)\1>'
text = '<h1>This is an example text.</h1>'
match = re.search(pattern, text)
if match:
print('Match found:', match.group(2))
else:
print('Match not found')
以上代碼在text中查找HTML標籤內容,輸出’Match found: This is an example text.’。
3. 匹配身份證號碼
import re
pattern = r'[1-9]\d{5}\d{4}(\d{4}|X|x)'
text = 'My ID number is 31234567890123456X'
match = re.search(pattern, text)
if match:
print('Match found:', match.group())
else:
print('Match not found')
以上代碼在text中查找身份證號碼,輸出’Match found: 31234567890123456X’。
五、總結
正則表達式在Python中是一個非常重要的概念和工具,可以用於字元串的匹配、查找和提取。在使用正則表達式時,建議使用Python的re模塊,並根據需要編寫相應的正則表達式規則。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/246355.html