正则表达式是一个强大且灵活的工具。它允许你根据模式匹配字符串,并进行搜索、替换和分割操作。在Python中,re
模块提供了对正则表达式的支持。
1. 导入模块
要使用正则表达式,首先需要导入Python的re
模块:
import re
2. 基本模式匹配
使用re
模块的search()
函数可以在字符串中搜索匹配的模式。
pattern = r"apple"
text = "I have an apple"
match = re.search(pattern, text)
if match:
print("找到匹配的字符串:", match.group())
else:
print("没有找到匹配的字符串")
r"apple"
:原始字符串,表示我们要匹配的模式是apple
。re.search(pattern, text)
:在text
中搜索符合pattern
的内容。match.group()
:返回匹配的字符串。
3. 匹配任意字符
.
可以匹配任意单个字符(除了换行符\n
)。
pattern = r"gr.y"
text1 = "grey"
text2 = "gray"
match1 = re.search(pattern, text1)
match2 = re.search(pattern, text2)
4. 匹配多个字符
*
:匹配前一个字符0次或多次。+
:匹配前一个字符1次或多次。?
:匹配前一个字符0次或1次。
pattern = r"ab*c"
text1 = "ac"
text2 = "abc"
text3 = "abbc"
match1 = re.search(pattern, text1)
match2 = re.search(pattern, text2)
match3 = re.search(pattern, text3)
5. 字符集
使用[]
指定一个字符集合。
pattern = r"[aeiou]"
text = "Hello"
match = re.search(pattern, text)
6. 匹配数字和非数字
\d
:匹配任何十进制数字。\D
:匹配任何非数字字符。
pattern = r"\d+"
text = "Age: 25"
match = re.search(pattern, text)
7. 边界匹配
^
:匹配字符串的开头。$
:匹配字符串的结尾。
pattern = r"^start"
pattern2 = r"end$"
text = "start and end"
match1 = re.search(pattern, text)
match2 = re.search(pattern2, text)
8. 分组
使用括号()
进行分组,以便捕获匹配的子字符串。
pattern = r"(\w+), (\w+)"
text = "Doe, John"
match = re.search(pattern, text)
if match:
print("Last name:", match.group(1))
print("First name:", match.group(2))
9. findall() 方法
re.findall()
方法可以找到所有匹配的字符串,返回一个列表。
pattern = r"\b\w{5}\b"
text = "Hello world, this is a test"
matches = re.findall(pattern, text)
10. 替换文本
使用re.sub()
进行文本替换。
pattern = r"apple"
text = "I have an apple"
new_text = re.sub(pattern, "orange", text)
print(new_text)
11.使用
1. 匹配邮箱地址
import re
pattern = r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b"
text = "我的邮箱是abc123@example.com,你的是xyz456@gmail.com。"
matches = re.findall(pattern, text)
print(matches)
解释:
\b
:表示单词边界,确保我们匹配的是整个邮箱地址而不是它的一部分。[A-Za-z0-9._%+-]+
:匹配邮件地址中的用户名部分,允许包含字母、数字、以及一些特定的字符@
:邮箱地址中的分隔符。[A-Za-z0-9.-]+
:匹配域名部分,允许包含字母、数字、.
和-
。\.
:匹配域名和顶级域名之间的点号。[A-Z|a-z]{2,}
:匹配顶级域名,至少两个字母长,可以是大写或小写字母。
2. 匹配日期格式
import re
pattern = r"\d{4}-\d{2}-\d{2}"
text = "今天是2023-01-15,明天是2023-01-16。"
matches = re.findall(pattern, text)
print(matches)
解释:
\d{4}
:匹配四个数字,表示年份。-
:日期中的分隔符。\d{2}
:匹配两个数字,表示月份和日期。
这个正则表达式可以有效地提取出字符串中所有的日期格式。
3. 匹配HTML标签中的文本内容
import re
html = "<p>This is <b>bold</b> and <i>italic</i> text</p>"
pattern = r"<.*?>"
text = re.sub(pattern, "", html)
print(text)
解释:
<.*?>
:这是一个非贪婪匹配,匹配任意字符(.*
),直到遇到第一个>
(?>
表示非贪婪模式),用来匹配HTML标签。re.sub(pattern, "", html)
:使用re.sub()
函数将匹配到的HTML标签替换为空字符串,从而得到纯文本内容。
4. 匹配手机号码
import re
pattern = r"1[3456789]\d{9}"
text = "我的电话号码是13912345678,他的是15678901234。"
matches = re.findall(pattern, text)
print(matches)
解释:
1[3456789]
:手机号码的开头必须是1,并且后面的数字可以是3、4、5、6、7、8、9中的任意一个。\d{9}
:后面跟着9个数字,共计11位,符合中国大陆手机号码的规范。