正則表達式(Regular Expression,簡稱 regex 或 regexp)是一種強大的文本處理工具,廣泛應用于字符串的搜索、匹配、替換等操作。Python 通過 re
模塊提供了對正則表達式的支持。本文將詳細介紹 Python 中正則表達式的常用語法,并通過實例分析幫助讀者更好地理解和掌握正則表達式的使用。
正則表達式是一種用于描述字符串模式的語法規則。通過正則表達式,我們可以快速地在文本中查找、匹配、替換符合特定模式的字符串。正則表達式廣泛應用于文本處理、數據清洗、日志分析等領域。
re
模塊Python 通過 re
模塊提供了對正則表達式的支持。re
模塊包含了正則表達式的編譯、匹配、搜索、替換等功能。以下是 re
模塊中常用的函數:
re.match(pattern, string)
:從字符串的起始位置匹配正則表達式。re.search(pattern, string)
:在字符串中搜索匹配正則表達式的第一個位置。re.findall(pattern, string)
:返回字符串中所有匹配正則表達式的子串。re.sub(pattern, repl, string)
:將字符串中匹配正則表達式的部分替換為指定字符串。re.compile(pattern)
:將正則表達式編譯為一個正則表達式對象,以便重復使用。正則表達式中的普通字符(如字母、數字、空格等)可以直接匹配字符串中的相應字符。例如,正則表達式 hello
可以匹配字符串 "hello world"
中的 "hello"
。
import re
pattern = r"hello"
text = "hello world"
match = re.search(pattern, text)
if match:
print("匹配成功:", match.group())
else:
print("匹配失敗")
輸出:
匹配成功: hello
字符集用于匹配一組字符中的任意一個。字符集用方括號 []
表示。例如,正則表達式 [aeiou]
可以匹配任意一個元音字母。
import re
pattern = r"[aeiou]"
text = "hello world"
matches = re.findall(pattern, text)
print("匹配的元音字母:", matches)
輸出:
匹配的元音字母: ['e', 'o', 'o']
正則表達式中的重復匹配用于指定某個字符或字符集的重復次數。常用的重復匹配符號包括:
*
:匹配前面的字符 0 次或多次。+
:匹配前面的字符 1 次或多次。?
:匹配前面的字符 0 次或 1 次。{n}
:匹配前面的字符恰好 n 次。{n,}
:匹配前面的字符至少 n 次。{n,m}
:匹配前面的字符至少 n 次,至多 m 次。import re
pattern = r"a{2,4}"
text = "aa, aaa, aaaa, aaaaa"
matches = re.findall(pattern, text)
print("匹配的a字符:", matches)
輸出:
匹配的a字符: ['aa', 'aaa', 'aaaa', 'aaaa']
邊界匹配用于指定匹配的位置,常用的邊界匹配符號包括:
^
:匹配字符串的開頭。$
:匹配字符串的結尾。\b
:匹配單詞的邊界。\B
:匹配非單詞的邊界。import re
pattern = r"\bhello\b"
text = "hello world, hello there, helloo"
matches = re.findall(pattern, text)
print("匹配的hello單詞:", matches)
輸出:
匹配的hello單詞: ['hello', 'hello']
分組用于將多個字符整體進行匹配,分組用圓括號 ()
表示。分組還可以用于捕獲匹配的子串,以便后續使用。
import re
pattern = r"(hello) (world)"
text = "hello world"
match = re.search(pattern, text)
if match:
print("匹配的完整字符串:", match.group())
print("第一個分組:", match.group(1))
print("第二個分組:", match.group(2))
輸出:
匹配的完整字符串: hello world
第一個分組: hello
第二個分組: world
正則表達式默認是貪婪匹配,即盡可能多地匹配字符。非貪婪匹配則盡可能少地匹配字符,非貪婪匹配在重復匹配符號后加上 ?
。
import re
pattern_greedy = r"a.*b"
pattern_non_greedy = r"a.*?b"
text = "aabab"
match_greedy = re.search(pattern_greedy, text)
match_non_greedy = re.search(pattern_non_greedy, text)
print("貪婪匹配:", match_greedy.group())
print("非貪婪匹配:", match_non_greedy.group())
輸出:
貪婪匹配: aabab
非貪婪匹配: aab
正則表達式中有一些特殊字符,用于表示特定的字符或字符集。常用的特殊字符包括:
.
:匹配任意單個字符(除換行符外)。\d
:匹配任意數字字符,等價于 [0-9]
。\D
:匹配任意非數字字符,等價于 [^0-9]
。\w
:匹配任意字母、數字或下劃線字符,等價于 [a-zA-Z0-9_]
。\W
:匹配任意非字母、數字或下劃線字符,等價于 [^a-zA-Z0-9_]
。\s
:匹配任意空白字符(包括空格、制表符、換行符等)。\S
:匹配任意非空白字符。import re
pattern = r"\d{3}-\d{2}-\d{4}"
text = "我的社保號是123-45-6789"
match = re.search(pattern, text)
if match:
print("匹配的社保號:", match.group())
輸出:
匹配的社保號: 123-45-6789
郵箱地址的格式通常為 username@domain.com
。我們可以使用以下正則表達式來匹配郵箱地址:
import re
pattern = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}"
text = "我的郵箱是user@example.com,請發郵件給我。"
match = re.search(pattern, text)
if match:
print("匹配的郵箱地址:", match.group())
輸出:
匹配的郵箱地址: user@example.com
URL 的格式通常為 http://www.example.com/path
。我們可以使用以下正則表達式來匹配 URL:
import re
pattern = r"https?://(?:www\.)?\S+"
text = "請訪問我們的網站https://www.example.com了解更多信息。"
match = re.search(pattern, text)
if match:
print("匹配的URL:", match.group())
輸出:
匹配的URL: https://www.example.com
IP 地址的格式通常為 192.168.1.1
。我們可以使用以下正則表達式來匹配 IP 地址:
import re
pattern = r"\b(?:\d{1,3}\.){3}\d{1,3}\b"
text = "服務器的IP地址是192.168.1.1。"
match = re.search(pattern, text)
if match:
print("匹配的IP地址:", match.group())
輸出:
匹配的IP地址: 192.168.1.1
日期的格式通常為 YYYY-MM-DD
。我們可以使用以下正則表達式來匹配日期:
import re
pattern = r"\d{4}-\d{2}-\d{2}"
text = "今天的日期是2023-10-05。"
match = re.search(pattern, text)
if match:
print("匹配的日期:", match.group())
輸出:
匹配的日期: 2023-10-05
HTML 標簽的格式通常為 <tag>content</tag>
。我們可以使用以下正則表達式來匹配 HTML 標簽:
import re
pattern = r"<(\w+)[^>]*>(.*?)</\1>"
text = "<h1>標題</h1><p>段落內容</p>"
matches = re.findall(pattern, text)
for tag, content in matches:
print(f"匹配的HTML標簽: <{tag}>{content}</{tag}>")
輸出:
匹配的HTML標簽: <h1>標題</h1>
匹配的HTML標簽: <p>段落內容</p>
手機號碼的格式通常為 13800138000
。我們可以使用以下正則表達式來匹配手機號碼:
import re
pattern = r"1[3-9]\d{9}"
text = "我的手機號碼是13800138000,請記下。"
match = re.search(pattern, text)
if match:
print("匹配的手機號碼:", match.group())
輸出:
匹配的手機號碼: 13800138000
條件匹配用于在正則表達式中根據條件選擇不同的匹配模式。條件匹配的語法為 (?(condition)true-pattern|false-pattern)
。
import re
pattern = r"(<)?(\w+@\w+(?:\.\w+)+)(?(1)>|$)"
text = "<user@example.com> user@example.com"
matches = re.findall(pattern, text)
for match in matches:
print("匹配的郵箱地址:", match[1])
輸出:
匹配的郵箱地址: user@example.com
匹配的郵箱地址: user@example.com
零寬斷言用于在匹配時指定某些條件,但不消耗字符。常用的零寬斷言包括:
(?=...)
:正向肯定預查。(?!...)
:正向否定預查。(?<=...)
:反向肯定預查。(?<!...)
:反向否定預查。import re
pattern = r"\b\w+(?=ing\b)"
text = "I am running and swimming."
matches = re.findall(pattern, text)
print("匹配的單詞:", matches)
輸出:
匹配的單詞: ['runn', 'swimm']
命名分組用于給分組命名,以便后續引用。命名分組的語法為 (?P<name>...)
。
import re
pattern = r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
text = "今天的日期是2023-10-05。"
match = re.search(pattern, text)
if match:
print("年份:", match.group("year"))
print("月份:", match.group("month"))
print("日期:", match.group("day"))
輸出:
年份: 2023
月份: 10
日期: 05
正則表達式的性能優化主要從以下幾個方面入手:
re.compile
進行預編譯。|
操作符。import re
pattern = re.compile(r"\d{3}-\d{2}-\d{4}")
text = "我的社保號是123-45-6789"
match = pattern.search(text)
if match:
print("匹配的社保號:", match.group())
輸出:
匹配的社保號: 123-45-6789
正則表達式是處理文本的強大工具,掌握正則表達式的語法和使用技巧可以極大地提高文本處理的效率。本文詳細介紹了 Python 中正則表達式的基本語法和常用實例,并探討了正則表達式的高級用法和性能優化技巧。希望本文能幫助讀者更好地理解和應用正則表達式。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。