import re
pattern ="apple"
text ="I like apples."match= re.search(pattern, text)ifmatch:print("匹配成功")else:print("匹配失败")
2.2 特殊字符
正则表达式中有一些特殊字符具有特殊含义,如.、*、+、?等。
.:匹配任意字符(除了换行符)。
*:匹配前一个字符0次或多次。
+:匹配前一个字符1次或多次。
?:匹配前一个字符0次或1次。
pattern ="a.*b"# 匹配以a开始,以b结束的任意字符序列
text ="aabb"match= re.search(pattern, text)ifmatch:print("匹配成功")else:print("匹配失败")
3. 正则表达式的元字符
元字符是正则表达式中具有特殊含义的字符,它们包括:
^:匹配字符串的开头。
$:匹配字符串的结尾。
[]:匹配括号中的任意一个字符。
|:或操作,匹配两者之一。
():捕获分组,将匹配的内容保存到变量中。
pattern =r"^[A-Za-z]+$"# 匹配由字母组成的字符串
text ="HelloWorld"match= re.search(pattern, text)ifmatch:print("匹配成功")else:print("匹配失败")
4. 正则表达式的预定义字符类
正则表达式提供了一些预定义字符类,用于匹配常见字符集合。
\d:匹配数字字符。
\D:匹配非数字字符。
\w:匹配单词字符(字母、数字、下划线)。
\W:匹配非单词字符。
\s:匹配空白字符(空格、制表符、换行符等)。
\S:匹配非空白字符。
pattern =r"\d{2}-\d{2}-\d{4}"# 匹配日期格式,如"09-18-2023"
text ="Today is 09-18-2023."match= re.search(pattern, text)ifmatch:print("匹配成功")else:print("匹配失败")
5. 正则表达式的重复限定符
正则表达式的重复限定符用于指定一个模式的重复次数。
{n}:匹配前一个字符恰好n次。
{n,}:匹配前一个字符至少n次。
{n,m}:匹配前一个字符至少n次,最多m次。
*:匹配前一个字符0次或多次。
+:匹配前一个字符1次或多次。
?:匹配前一个字符0次或1次。
pattern =r"\d{3}-\d{2}-\d{4}"# 匹配社会安全号码,如"123-45-6789"
text ="My SSN is 123-45-6789."match= re.search(pattern, text)ifmatch:print("匹配成功")else:print("匹配失败")
pattern =r"(\d{2})-(\d{2})-(\d{4})"# 匹配日期,分为年、月、日三个分组
text ="Today is 09-18-2023."match= re.search(pattern, text)ifmatch:
year =match.group(3)
month =match.group(2)
day =match.group(1)print(f"Year: {year}, Month: {month}, Day: {day}")
8. Python中的正则表达式操作
Python的re模块提供了一系列函数来操作正则表达式,包括:
re.search():在字符串中搜索匹配项。
re.match():在字符串的开头匹配。
re.findall():返回字符串中所有匹配项。
re.finditer():返回匹配项的迭代器。
re.sub():替换匹配项。
re.split():根据正则表达式拆分字符串。
import re
pattern =r"\d+"
text ="The price of the book is $15.99."
matches = re.findall(pattern, text)print(matches)# 输出:['15', '99']
new_text = re.sub(pattern,"XX", text)print(new_text)# 输出:"The price of the book is $XX."
pattern =r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
text ="Today is 2023-09-18."match= re.search(pattern, text)ifmatch:
year =match.group("year")
month =match.group("month")
day =match.group("day")print(f"Year: {year}, Month: {month}, Day: {day}")
9.4 非捕获组
可以使用(?:...)语法来创建非捕获组,即不捕获匹配的内容。
pattern =r"(?:Mr.|Mrs.) (\w+)"# 匹配Mr.或Mrs.后面的单词字符
text ="Mr. Smith and Mrs. Johnson"
matches = re.findall(pattern, text)print(matches)# 输出:['Smith', 'Johnson']
10. 实际应用示例
10.1 邮箱验证
import re
defis_valid_email(email):
pattern =r"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,}$"return re.match(pattern, email)isnotNone
email ="user@example.com"if is_valid_email(email):print("邮箱地址有效")else:print("邮箱地址无效")
10.2 HTML标签提取
import re
defextract_html_tags(html):
pattern =r"<[^>]+>"return re.findall(pattern, html)
html ="<div><p>Hello, World!</p></div>"
tags = extract_html_tags(html)print(tags)# 输出:['<div>', '<p>', '</p>', '</div>']
10.3 日志分析
import re
log ="""
[INFO] User Alice logged in.
[ERROR] Connection failed for user Bob.
[INFO] User Carol logged in.
"""
pattern =r"[([A-Z]+)] ([^\n]+)"
matches = re.findall(pattern, log)formatchin matches:
level, message =matchprint(f"Level: {level}, Message: {message}")