Python是一門強大的編程語言,它支持正則表達式操作,正則表達式是在文本中匹配模式的一種工具。在Python中使用正則表達式可以在文本中進行字元串查找、替換等操作。接下來,本文將為大家介紹Python Regex的定義及使用方法。
一、正則表達式概述
正則表達式是一種用來描述、匹配一系列符合某個規則的字元串的方法。在正則表達式中,使用特殊的字元表示具有特殊意義的內容,如”.”用來匹配任意字元,”*”表示匹配0次或多次,”?”表示匹配0次或1次等等。Python中的正則表達式需要使用re模塊進行調用。
二、常用正則表達式函數
在Python中,re模塊提供了多個用於正則表達式操作的函數,其中常用的函數如下:
1. re.match()
re.match()函數用於嘗試從字元串的起始位置開始匹配一個模式,如果匹配成功,則返回匹配對象;否則返回None。例如:
import re str = "hello world" matchObj = re.match(r'hello', str, re.M | re.I) if matchObj: print("matchObj.group() : ", matchObj.group()) else: print("No match!!")
該代碼會輸出”matchObj.group() : hello”,因為正則表達式r’hello’匹配了字元串的起始位置的”hello”。
2. re.search()
re.search()函數用於在字元串中搜索匹配表達式第一次出現的位置,如果匹配成功,則返回匹配對象;否則返回None。例如:
import re str = "hello world" searchObj = re.search(r'world', str, re.M | re.I) if searchObj: print("searchObj.group() : ", searchObj.group()) else: print("Nothing found!!")
該代碼會輸出”searchObj.group() : world”,因為正則表達式r’world’匹配了字元串中的”world”。
3. re.findall()
re.findall()函數用於返回字元串中所有與正則表達式匹配的字元串列表,如果沒有匹配的,則返回空列表。例如:
import re str = "hello world" findallObj = re.findall(r'\w{5}', str, re.M | re.I) print("findallObj : ", findallObj)
該代碼會輸出”findallObj : [‘hello’, ‘world’]”,因為正則表達式r’\w{5}’匹配了字元串中的”hello”和”world”。
4. re.sub()
re.sub()函數用於在字元串中替換所有與正則表達式匹配的子串,並返回替換後的新字元串。例如:
import re str = "hello world" subObj = re.sub(r'world', 'Python', str, re.M | re.I) print("subObj : ", subObj)
該代碼會輸出”subObj : hello Python”,因為正則表達式r’world’匹配了字元串中的”world”,並被替換成了”Python”。
三、常用正則表達式語法
在Python中,正則表達式的語法非常豐富,下面列舉一些常用的語法:
1. 圓括弧()
圓括弧可以將正則表達式中的一部分括起來,形成一個子組,可以使用matches.group()函數獲取子組的值。例如:
import re str = "hello 123 world" matchObj = re.match(r'h(.*?) (\d+)', str, re.M | re.I) if matchObj: print("matchObj.group() : ", matchObj.group()) print("matchObj.group(1) : ", matchObj.group(1)) print("matchObj.group(2) : ", matchObj.group(2)) else: print("No match!!")
該代碼會輸出”matchObj.group() : hello 123″、”matchObj.group(1) : ello”和”matchObj.group(2) : 123″,因為正則表達式r’h(.*?) (\d+)’中的”(.*?)”和”(\d+)”被括起來形成了兩個子組,可以使用matches.group(1)和matches.group(2)函數獲取子組值。
2. 方括弧[]
方括弧可以將字符集合起來,表示匹配方括弧中的任意一個字元。例如:
import re str = "hello world" matchObj = re.match(r'[helo]+', str, re.M | re.I) if matchObj: print("matchObj.group() : ", matchObj.group()) else: print("No match!!")
該代碼會輸出”matchObj.group() : hello”,因為正則表達式r'[helo]+’表示匹配”h”、”e”、”l”或者”o”中的任意個一個字元。
3. 反斜杠轉義字元
反斜杠可以用來轉義字元,表示其後面的字元應該被視為普通字元而非特殊字元。例如:
import re str = "hello world.+" matchObj = re.match(r'hello world\.\+', str, re.M | re.I) if matchObj: print("matchObj.group() : ", matchObj.group()) else: print("No match!!")
該代碼會輸出”matchObj.group() : hello world.+”,因為”.”和”+”在正則表達式中有特殊含義,但是在它們前面加上反斜杠後,就被視為普通字元了。
四、常用正則表達式實例
下面列舉一些使用Python正則表達式的實例:
1. 郵箱驗證
import re def validate_email(email): regex = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$' if re.match(regex, email): return True else: return False print(validate_email("123456@qq.com")) # True print(validate_email("abc_123@gmail.com")) # True print(validate_email("abc#123.com")) # False
該代碼使用正則表達式驗證郵箱格式是否正確,如果正確則返回True否則返回False。其中正則表達式r’^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$’表示匹配由A-Z、a-z、0-9、正號、負號、下劃線、點組成的email地址格式。
2. URL提取
import re def get_urls(text): urls = [] regex = r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+' matches = re.findall(regex, text) for match in matches: urls.append(match) return urls print(get_urls("hello world, http://www.google.com is a search engine.")) # ['http://www.google.com'] print(get_urls("Download from http://www.github.com")) # ['http://www.github.com']
該代碼使用正則表達式從文本中提取URL地址。
總結
Python中的正則表達式提供了非常強大的文本匹配和處理功能,學習和掌握正則表達式是Python編程中的重要一環。本文介紹了正則表達式的常用函數和語法,並給出了一些實用的示例。希望讀者們能夠在日常Python編程中加以應用。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187232.html