正则表达式(regular expression,re):一种用于匹配、查找或替换文本中特定模式的强大工具。
一、re的核心语法
1、基本匹配
| 语法 | 说明 | 示例(表达式 → 匹配示例) |
|---|---|---|
abc | 匹配字面值 "abc" | "abc" → "abc" |
. | 匹配任意单个字符(除换行符 \n) | "a.c" → "abc", "a c" |
\ | 转义特殊字符(如 \. 匹配点号) | "a\.c" → "a.c" |
| | 或逻辑(匹配左边或右边的表达式) | "cat|dog" → "cat" 或 "dog" |
2、字符类
| 语法 | 说明 | 示例(表达式 → 匹配示例) |
|---|---|---|
[abc] | 匹配 a、b 或 c | "[aeiou]" → "e" in "hello" |
[^abc] | 匹配非 a、b、c 的字符 | "[^0-9]" → "a" in "a1" |
[a-z] | 匹配小写字母(范围) | "[a-z]" → "h" in "hi" |
[a-z0-9] | 匹配大写字母或数字 | "[a-z0-9]" → "h", "1" |
3、量词(重复匹配)
| 语法 | 说明 | 示例(表达式 → 匹配示例) |
|---|---|---|
* | 匹配前一项 0次或多次 | "a*" → "", "aaa" |
+ | 匹配前一项 1次或多次 | "a+" → "a", "aaa" |
? | 匹配前一项 0次或1次 | "a?" → "", "a" |
{n} | 匹配前一项 恰好n次 | "a{2}" → "aa" |
{n,} | 匹配前一项 至少n次 | "a{2,}" → "aaa" |
{n,m} | 匹配前一项 n到m次 | "a{2,3}" → "aa", "aaa" |
4、贪婪 vs 非贪婪
| 语法 | 说明 | 示例(表达式 → 匹配示例) |
|---|---|---|
* | 贪婪匹配(尽可能多) | "a.*b" → "aabb" in "aabbaab" |
*? | 非贪婪匹配(尽可能少) | "a.*?b" → "aab" in "aabbaab" |
+? | 非贪婪的 + | "a.+?b" → "aab" |
5、预定义字符类
| 语法 | 说明 | 等价写法 → 匹配示例 |
|---|---|---|
\d | 数字([0-9]) | "a\d" → "a1" |
\d | 非数字([^0-9]) | "a\d" → "ab" |
\w | 单词字符([a-za-z0-9_]) | "\w+" → "word_" |
\w | 非单词字符 | "\w" → "!" |
\s | 空白字符(空格、制表符等) | "a\sb" → "a b" |
\s | 非空白字符 | "a\sb" → "a1b" |
6、边界匹配
| 语法 | 说明 | 示例(表达式 → 匹配示例) |
|---|---|---|
^ | 匹配字符串开头 | "^a" → "a" in "abc" |
$ | 匹配字符串结尾 | "c$" → "c" in "abc" |
二、python的 re 库中常用的基本方法
1、核心匹配方法
| 方法 | 语法 | 返回值 | 功能说明 | 示例 |
|---|---|---|---|---|
re.match() | re.match(pattern, string) | match 对象或 none | 从字符串开头匹配 | re.match(r'\d+', '123abc').group() → '123' |
re.search() | re.search(pattern, string) | match 对象或 none | 扫描整个字符串匹配第一个 | re.search(r'\d+', 'abc123').group() → '123' |
re.findall() | re.findall(pattern, string) | 列表 | 返回所有匹配的子串 | re.findall(r'\d+', 'a1b22c333') → ['1', '22', '333'] |
代码示例:
# match()方法错误示范
text = "邮箱:user.lili-103@example.com"
email_pattern = r'^[a-za-z0-9.-]+@[a-za-z0-9.-]+\.[a-za-z]{2,}$'
res = re.match(email_pattern, text)
if res:
print(res.group())
# 没有输出,因为文本开头是邮箱,而match()方法只从字符串开头匹配正则表达式,res为none
# match()方法正确使用:修改text,或使用search()方法
text = "user.lili-103@example.com"
email_pattern = r'^[a-za-z0-9.-]+@[a-za-z0-9.-]+\.[a-za-z]{2,}$'
res = re.match(email_pattern, text)
if res:
print(res.group())
# 输出为:user.lili-103@example.com# search()
text = "abc123def456"
result = re.search(r'\d+', text) # 查找第一个数字序列
if result:
print("找到数字:", result.group()) # 输出: 123
else:
print("未找到数字")# findall()
text = "a156b22c333d"
results = re.findall(r'\d+', text) # 查找所有数字序列
print("所有数字:", results) # 输出: ['156', '22', '333']注:.group()方法用于提取匹配的内容。如re.match()方法返回结果的是match 对象,而不是匹配的内容,需要使用group()提取匹配内容。
2. 替换与分割
| 方法 | 语法 | 返回值 | 功能说明 | 示例 |
|---|---|---|---|---|
re.sub() | re.sub(pattern, repl, string, count=0) | 字符串 | 替换匹配的子串。
| re.sub(r'\d+', 'x', 'a1b22') → 'axbx' |
re.split() | re.split(pattern, string, maxsplit=0) | 列表 | 按正则表达式分割字符串 | re.split(r'\d+', 'a1b22c3') → ['a', 'b', 'c', ''] |
代码示例:
import re # 替换所有匹配项 text = "python is great. python is easy." result = re.sub(r'python', 'java', text) print(result) # 输出: "java is great. java is easy." # 只替换第一个 result = re.sub(r'python', 'java', text, count=1) print(result) # 输出: "java is great. python is easy."
text = "apple?banana,cherry.egg right" result = re.split(r'[,.? ]', text) # 按[,.? ]分割 print(result) # 输出: ['apple', 'banana', 'cherry', 'egg'] result = re.split(r'[,.? ]', text, maxsplit=1) # 只分割一次 print(result) # 输出: ['apple', 'banana,cherry.egg right']
三、不同场景的变体
宽松模式(匹配更多,包括新顶级域):
re.findall(r'[\w\.\-]+@[\w\-]+(?:\.[\w\-]+)+', text)
严格模式(仅匹配常用域名后缀,如 com, org, net, edu, cn 等):
re.findall(r'[\w\.\-]+@[\w\-]+\.(?:com|org|net|edu|cn|co\.uk)', text, re.i)
从 html/网页中提取(避免匹配标签内的假邮箱):
可先使用beautifulsoup解析文本内容,再应用上述正则。实时输入验证(判断一个字符串是否是合法邮箱):
def is_valid_email(email: str) -> bool: return bool(email_regex.fullmatch(email.strip()))
总结
到此这篇关于正则表达式核心语法以及python的re库中常用方法总结的文章就介绍到这了,更多相关python正则表达式re库方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论