Python 正則表達式是一種強大的工具,可以有效地匹配和查找文本信息。正則表達式是由一系列字符和符號組成的模式,用於匹配和識別字符串。在 Python 中,可以使用 re 模塊來使用正則表達式。
一、正則表達式基礎
正則表達式由一些簡單字符和特殊字符(元字符)組成。簡單字符包括字母、數字和普通標點符號等。而元字符則有特殊的含義,用來匹配一些具有特定規律的字符串。
下面是一些常用的正則表達式元字符:
. 匹配任意一個字符 ^ 匹配字符串的開頭 $ 匹配字符串的結尾 * 匹配前面的字符 0 次或多次 + 匹配前面的字符 1 次或多次 ? 匹配前面的字符 0 次或 1 次 {m,n} 匹配前面的字符 m 次到 n 次 [...] 匹配中括號中的任意一個字符
正則表達式還支持使用括號進行分組,以及使用 | 符號表示或關係。
下面是一個簡單的例子,用於匹配 email 地址:
import re email_regex = r"[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" email = "example@example.com" if re.match(email_regex, email): print("Valid email!") else: print("Invalid email!")
這個正則表達式可以匹配類似於 example@example.com 這樣的 email 地址。其中,+ 表示前面的字符可以出現一次或多次,\ 表示對 . 進行轉義。
二、常用正則表達式方法
在 re 模塊中,有一系列可以使用的方法來使用正則表達式。下面是一些常用的方法:
1. re.match()
re.match() 方法用於檢查字符串是否以給定正則表達式匹配開頭。如果匹配成功,則返回一個匹配對象;否則返回 None。
import re phone_regex = r"^(\d{3})-(\d{8})$" phone1 = "010-12345678" phone2 = "12345678" match1 = re.match(phone_regex, phone1) match2 = re.match(phone_regex, phone2) if match1: print("Valid phone number!") else: print("Invalid phone number!") if match2: print("Valid phone number!") else: print("Invalid phone number!")
這個例子中,我們使用 re.match() 方法來匹配類似於 010-12345678 這樣的電話號碼。其中,^ 表示字符串的開始位置,() 表示分組。
2. re.search()
re.search() 方法用於檢查字符串中是否存在一個匹配正則表達式的子串。需要注意的是,re.search() 只匹配到第一個匹配項就會停止匹配。
import re sentence_regex = r"is [a-zA-Z]+" sentence1 = "This is a sentence." sentence2 = "Is this a sentence?" search1 = re.search(sentence_regex, sentence1) search2 = re.search(sentence_regex, sentence2) if search1: print("Match found in sentence1!") else: print("No match found in sentence1!") if search2: print("Match found in sentence2!") else: print("No match found in sentence2!")
這個例子中,我們使用 re.search() 方法來查找類似於 is a 這樣的字串。[a-zA-Z]+ 表示匹配一個或多個字母。
3. re.findall()
re.findall() 方法返回字符串中所有與正則表達式匹配的子串。
import re filename_regex = r"\w+\.txt" files = "abc.txt 123.txt def.pdf" matches = re.findall(filename_regex, files) print(matches)
這個例子中,我們使用 re.findall() 方法來查找字符串中所有以 .txt 結尾的文件名。
三、正則表達式的高級用法
正則表達式還支持一些高級用法,如負向前瞻、分組和替換。
1. 負向前瞻
負向前瞻是指在匹配時,判斷前面是否存在某個模式,如果不存在,則繼續匹配後面的字符串。
import re password_regex = r"(?=\w{8,})(?=\D*\d)(?=[^A-Z]*[A-Z])\w+" password1 = "1aBcDdEf" password2 = "12abcdefg" if re.match(password_regex, password1): print("Valid password!") if re.match(password_regex, password2): print("Valid password!") else: print("Invalid password!")
這個例子中,我們使用正則表達式和負向前瞻來驗證密碼的強度。其中,\w 表示字母和數字,\D 表示非數字,[^A-Z] 表示非大寫字母。
2. 分組
正則表達式支持使用括號進行分組。
import re string = "hello world" match = re.match(r"(\w+) (\w+)", string) if match: print(match.group(1)) print(match.group(2))
這個例子中,我們使用正則表達式和分組來匹配 hello 和 world 這兩個單詞。
3. 替換
正則表達式還支持替換操作。
import re string = "hello world" new_string = re.sub(r"(\w+)", r"\1", string) print(new_string)
這個例子中,我們使用正則表達式和替換操作來將文本中的單詞加粗。
四、結語
Python 正則表達式是一種非常強大的工具,可以有效地匹配和查找文本信息。通過本文的介紹,相信讀者已經對 Python 正則表達式有了更深入的了解。在實際開發中,需要根據具體情況靈活使用正則表達式來完成文本處理任務。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/239425.html