在Python編程中,正則表達式是很重要的一部分,因為它可以用來處理字元串以及文本數據。在這篇文章中,我們將介紹Python正則表達式的一些基本概念、常用函數及應用舉例。
一、正則表達式基本概念
正則表達式是一種特殊的字元序列,它可以用來匹配出符合某種模式的字元串。正則表達式中常用的符號有:
– `.`:匹配任意一個字元。
– `*`:表示匹配0個或多個字元。
– `+`:表示匹配1個或多個字元。
– `?`:表示匹配0個或1個字元。
– `{}`:表示匹配指定的重複次數。
– `[]`:表示匹配指定的字符集合。
– `\`:用來轉義特殊字元,例如`\d`表示匹配數字。
在Python中,使用`re`模塊來操作正則表達式,常用函數有:
– `re.compile(pattern)`:將正則表達式編譯成一個Pattern對象,可以重複使用。
– `re.search(pattern, string)`:在string中搜索匹配pattern的第一個位置,並返回一個Match對象。如果沒有找到匹配的位置,則返回None。
– `re.match(pattern, string)`:同search(),但只從string的開始位置進行匹配。
– `re.findall(pattern, string)`:搜索string,以列表形式返回所有匹配的字元串。
– `re.finditer(pattern, string)`:搜索string,返回一個匹配結果的迭代器。
– `re.sub(pattern, repl, string)`:使用repl替換string中所有匹配pattern的子串,返回替換後的字元串。
下面給出一些基本的正則表達式示例:
import re
# 匹配數字
pattern = r'\d+'
text = 'I have 100 dollars and 20 cents.'
result = re.findall(pattern, text)
print(result) # ['100', '20']
# 匹配電子郵件地址
pattern = r'\w+@\w+\.\w+'
text = 'My email is abc123@gmail.com.'
result = re.findall(pattern, text)
print(result) # ['abc123@gmail.com']
# 匹配電話號碼
pattern = r'\d{3}-\d{3}-\d{4}'
text = 'My phone number is 123-456-7890.'
result = re.findall(pattern, text)
print(result) # ['123-456-7890']
二、正則表達式擴展用法
除了基本正則表達式外,還有一些擴展用法可以用來處理更複雜的匹配模式:
– `(pattern)`:表示捕獲分組,可以將匹配的子串保存到變數中。
– `(\d+)`:表示捕獲分組,只匹配數字。
– `\1`:表示反向引用,引用第1個捕獲分組的內容。
– `(?:pattern)`:表示非捕獲分組,用於提高效率。
– `(?=pattern)`:表示正向預查,在匹配pattern的情況下,要求緊隨其後的字元也符合條件。
– `(?!pattern)`:表示負向預查,在不匹配pattern的情況下,才匹配緊隨其後的字元。
下面給出一個關於正則表達式擴展用法的示例:
import re
# 處理HTML標籤
html = '<div class="container"><p>Hello, world!</p></div>'
pattern = r'<.*?>(.*)</.*?>'
result = re.findall(pattern, html)
print(result) # ['Hello, world!']
# 搜索相鄰單詞
text = 'I love Python programming, how about you?'
pattern = r'\b(\w+)\b\s+(?=\1)'
result = re.findall(pattern, text)
print(result) # ['Python']
#查找連續重複的字元
text = 'aaaabbbbccccddddd'
pattern = r'(\w)\1+'
result = re.findall(pattern, text)
print(result) # ['aaaa', 'bbbb', 'cccc', 'ddddd']
三、正則表達式應用舉例
正則表達式在文本處理中有廣泛的應用,例如:
– 郵箱地址的校驗,驗證用戶輸入的是否符合指定格式。
– 爬蟲中對返回的HTML文本進行解析,提取需要的內容。
– 日誌文件中提取特定的記錄,從而進行分析。
– 敏感詞過濾,過濾掉一些敏感的關鍵字,例如色情、暴力、政治敏感等。
– 資料庫中的模糊查詢,快速地查找符合某種模式的數據。
下面給出一些正則表達式應用的示例:
import re
# 郵箱地址校驗
pattern = r'\w+@\w+\.\w+'
email = 'abc123@gmail.com'
if re.match(pattern, email):
print('Email address is valid.')
else:
print('Email address is not valid.')
# 爬蟲中的正則表達式解析
import requests
url = 'https://www.baidu.com'
resp = requests.get(url)
text = resp.text
pattern = r'(.*?) '
result = re.search(pattern, text)
print(result.group(1)) # '百度一下,你就知道'
# 日誌文件記錄提取
log = '2022-01-01 10:05:20 INFO [example.py] Some message log.'
pattern = r'(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}).(\w+)\[(.*?)\](.*)'
result = re.findall(pattern, log)
for item in result:
print(item)
# 敏感詞過濾
pattern = r'色情|暴力|政治'
text = '今天看見一些色情的畫面,感覺很不舒服。'
result = re.sub(pattern, '**', text)
print(result) # '今天看見一些**的畫面,感覺很不舒服。'
# 資料庫中的模糊查詢
import sqlite3
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute("SELECT * FROM users WHERE name LIKE 'Mike%'")
result = cursor.fetchall()
print(result)
conn.close()
以上就是Python正則表達式函數的介紹及應用舉例。在實際編程中,正則表達式是一種強大的工具,掌握它可以大大提高我們數據處理的效率。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/291971.html