一、Python3正則表達式匹配
Python中re模塊提供多種與正則表達式相關的操作。其中最基本的操作就是匹配。使用re模塊的match()函數進行匹配,如果字元串開頭匹配成功,則返回一個匹配對象,否則返回None。
import re text = "This is a sample text" pattern = "This.*text" match_obj = re.match(pattern, text) if match_obj: print("Match found: ", match_obj.group()) else: print("No match found")
使用re模塊的search()函數進行匹配,函數在字元串中搜索匹配項。如果搜索到,則返回一個匹配對象,否則返回None。
import re text = "This is a sample text" pattern = "sample" match_obj = re.search(pattern, text) if match_obj: print("Match found: ", match_obj.group()) else: print("No match found")
使用re模塊的findall()函數找到所有匹配的項並以列表形式返回。如果沒有找到匹配,返回空列表。
import re text = "This is a sample text with matches" pattern = "is" match_list = re.findall(pattern, text) print("Match found: ", match_list)
二、Python3正則表達式r的作用
在Python中,在正則表達式字元串之前加上”r”,會將該字元串視為原始字元串,即忽略其中的轉義字元。
import re pattern = "\t" match_obj = re.search(pattern, "This is a\t sample text with matches") print("Match found: ", match_obj.group()) pattern = r"\t" match_obj = re.search(pattern, "This is a\t sample text with matches") print("Match found: ", match_obj.group())
三、Python3正則表達式匹配回車符
在Python中,除了普通字元外,還有一些特殊字元,例如:\n、\r、\t等。匹配這些特殊字元需要使用對應的轉義字元。\r(回車符)也是一個特殊字元,需要使用轉義字元進行匹配。
import re pattern = r"\r" match_obj = re.search(pattern, "This is a sample text with \rmatches") print("Match found: ", match_obj.group())
四、Python正則表達式的作用
Python正則表達式是一種文本模式,它可以用來匹配、替換特定的文本。Python正則表達式通常用於數據處理、文本處理、爬蟲、網路編程等方面。
五、Python正則表達式應用
Python正則表達式的應用非常廣泛,以下是一些實際應用場景:
1、抓取HTML、XML等頁面中的數據
import re import requests url = "https://www.example.com" response = requests.get(url) pattern = r"(.*)" match_obj = re.search(pattern, response.text) if match_obj: print(match_obj.group(1))
2、提取JSON數據中的特定欄位
import re import json json_string = '{"name":"Alice", "age":25, "gender":"female"}' pattern = r'"name":"(\w+)"' match_obj = re.search(pattern, json_string) if match_obj: print(match_obj.group(1))
3、過濾不符合條件的數據
import re pattern = r"^(\d{4})-(\d{1,2})-(\d{1,2})$" date_list = ["2019-10-01", "2019-20-02", "2019-03-31", "2019-04-31"] for date in date_list: match_obj = re.search(pattern, date) if match_obj: print(match_obj.group())
六、Python3正則表達式教程
如果您需要更深入的學習Python正則表達式,可以參考Python官方文檔中關於re模塊的內容,這裡提供一個鏈接:
https://docs.python.org/3/library/re.html
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/254735.html