08_正则表达式
第8课:正则表达式
课程目标
- 理解正则表达式的基本概念
- 掌握常用的正则表达式模式
- 学习Python中re模块的使用
- 能够编写简单的正则表达式
1. 正则表达式基础
1.1 什么是正则表达式
正则表达式是一种用于匹配字符串模式的工具,可以用于搜索、替换和验证文本。
1.2 基本语法
import re# 基本匹配
text = "Hello, World!"
pattern = r"Hello"
match = re.search(pattern, text)
if match:print("找到匹配:", match.group())
2. 常用模式
2.1 字符类
import retext = "The cat sat on the mat."# 匹配单个字符
pattern = r"cat"
matches = re.findall(pattern, text)
print("匹配结果:", matches) # ['cat']# 字符类 [abc] 匹配a、b或c中的任意一个
pattern = r"[cat]"
matches = re.findall(pattern, text)
print("字符类匹配:", matches)# 范围字符类 [a-z] 匹配小写字母
pattern = r"[a-z]+"
matches = re.findall(pattern, text)
print("小写字母匹配:", matches)# 否定字符类 [^abc] 匹配除了a、b、c之外的字符
pattern = r"[^aeiou\s]+"
matches = re.findall(pattern, text)
print("非元音字母匹配:", matches)
2.2 量词
import retext = "aaabbbcccddd"# * 匹配0个或多个
pattern = r"a*"
matches = re.findall(pattern, text)
print("a*匹配:", matches)# + 匹配1个或多个
pattern = r"a+"
matches = re.findall(pattern, text)
print("a+匹配:", matches)# ? 匹配0个或1个
pattern = r"a?"
matches = re.findall(pattern, text)
print("a?匹配:", matches)# {n} 匹配恰好n个
pattern = r"a{3}"
matches = re.findall(pattern, text)
print("a{3}匹配:", matches)# {n,m} 匹配n到m个
pattern = r"a{2,4}"
matches = re.findall(pattern, text)
print("a{2,4}匹配:", matches)
2.3 特殊字符
import retext = "Hello\nWorld\tPython"# \d 匹配数字
pattern = r"\d+"
matches = re.findall(pattern, text)
print("数字匹配:", matches)# \w 匹配单词字符(字母、数字、下划线)
pattern = r"\w+"
matches = re.findall(pattern, text)
print("单词字符匹配:", matches)# \s 匹配空白字符
pattern = r"\s+"
matches = re.findall(pattern, text)
pri