正则表达式(Regular Expression,简称 regex 或 regexp)是一种强大的文本处理工具,广泛应用于各种编程语言和工具中。它能够帮助我们轻松地处理非字符匹配难题,无论是搜索、替换、验证还是提取特定模式的数据,正则表达式都能提供高效且灵活的解决方案。本文将详细介绍正则表达式的基本概念、常用元字符、高级技巧以及实战案例,帮助读者从入门到精通。
第一部分:正则表达式基础
1. 什么是正则表达式?
正则表达式是一种描述字符串模式的语言。它允许你定义一个模式,然后用这个模式来匹配、查找、替换或验证字符串。正则表达式通常用于文本处理任务,如搜索和替换文本中的特定模式。
2. 正则表达式的组成
正则表达式由普通字符和特殊字符组成。普通字符代表它们自身,而特殊字符具有特定的意义。
3. 正则表达式的执行过程
正则表达式从左到右进行匹配,直到找到符合整个模式的字符串为止。
第二部分:常用正则表达式元字符
1. 点号(.)
点号(.)可以匹配除换行符以外的任何单个字符。
import re
pattern = r’.’
text = “Hello, World!”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘,’, ‘ ‘, ‘W’, ‘o’, ‘r’, ‘l’, ‘d’, ‘!’]
2. 星号(*)
星号(*)表示匹配前面的子表达式零次或多次。
pattern = r’he*o’
text = “heoheohe”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘heo’, ‘heo’, ‘he’]
3. 加号(+)
加号(+)表示匹配前面的子表达式一次或多次。
pattern = r’he+o’
text = “heoheohe”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘heo’, ‘heo’, ‘heo’]
4. 问号(?)
问号(?)表示匹配前面的子表达式零次或一次。
pattern = r’he?o’
text = “heoheohe”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘heo’, ‘o’, ‘heo’, ‘heo’, ‘he’]
5. 花括号({})
花括号({})用于指定匹配次数。
pattern = r’he{2}o’
text = “heoheohe”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘heoheo’]
6. 方括号([])
方括号([])用于匹配一组字符中的任意一个。
pattern = r'[aeiou]’
text = “Hello, World!”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘e’, ‘o’, ‘o’, ‘o’]
7. 脱字符(^)
脱字符(^)表示匹配输入字符串的开始位置。
pattern = r’^Hello’
text = “Hello, World!”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘Hello’]
8. 美元符号($)
美元符号($)表示匹配输入字符串的结束位置。
pattern = r’World$’
text = “Hello, World!”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘World!’]
第三部分:高级正则表达式技巧
1. 捕获组
捕获组用于提取匹配的子字符串。
pattern = r'(\d{4})-(\d{2})-(\d{2})’
text = “2023-04-01”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘2023′, ’04’, ’01’]
2. 反向引用
反向引用用于引用之前匹配的子表达式。
pattern = r'(\d{2})-(\d{2})-(\d{4})’
text = “04-01-2023”
matches = re.findall(pattern, text)
print(matches) # 输出: [’04’, ’01’, ‘2023’]
print(“Year: ” + matches[2]) # 输出: Year: 2023
3. 非捕获组
非捕获组用于匹配但不保存匹配的子字符串。
pattern = r'(?:(\d{2})-(\d{2})-(\d{4}))’
text = “04-01-2023”
matches = re.findall(pattern, text)
print(matches) # 输出: [’04-01-2023′]
4. 前瞻断言与后瞻断言
前瞻断言和后瞻断言用于匹配符合特定条件的字符串,但不消耗任何字符。
pattern = r'(?=\d{4}-\d{2}-\d{2})’
text = “2023-04-01”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘2023-04-01′]
5. 贪婪与非贪婪模式
贪婪模式匹配尽可能多的字符,而非贪婪模式匹配尽可能少的字符。
pattern = r’0*(\d+)’
text = “00432”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘432′]
第四部分:正则表达式实战案例
1. 电子邮件地址验证
pattern = r’^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$’
text = “example@example.com”
matches = re.match(pattern, text)
print(matches) # 输出:
2. 电话号码提取
pattern = r’\d{3}-\d{3}-\d{4}’
text = “123-456-7890”
matches = re.findall(pattern, text)
print(matches) # 输出: [‘123-456-7890′]
3. HTML标签清理
pattern = r’<[^>]+>’
text = “
world