智能生成和解释正则表达式,支持各种常见模式匹配
将您的文字指令转换为公式,或输入公式获取解释。
通过和AI对话来在线编辑Excel
使用AI将您的文字指令转换为SQL查询语句。
生成Excel VBA(Visual Basic for Applications)代码,用于自动化任务和创建Microsoft Excel中的自定义解决方案。
上传您的Excel文件,使用我们的AI驱动的图表生成器生成漂亮的图表。
使用我们的AI驱动的思维导图生成器将您的文本转换为漂亮的思维导图。轻松编辑和自定义您的思维导图。
使用AI智能生成和解释正则表达式,支持各种文本模式匹配和数据验证。
使用AI根据文字描述生成精美图片,支持多种尺寸,免费
正则表达式是文本处理的强大工具,在Python数据分析、网络爬虫和日志处理等领域有广泛应用。本教程将带你系统掌握Python中的re模块,并通过实际案例演示如何高效处理文本数据。
正则表达式在数据处理中扮演着重要角色:
研究表明,专业开发者在文本处理任务中使用正则表达式可以显著提升工作效率,特别是在处理复杂文本模式时。
import re
pattern = r"hello"
text = "hello world"
result = re.match(pattern, text)
if result:
print("匹配成功:", result.group()) # 输出: hello
text = "Python最新版本3.9发布了"
match = re.search(r'\d+.\d+', text)
if match:
print("发现版本号:", match.group()) # 输出: 3.9
contact_info = "邮箱: [email protected], 客服: [email protected]"
emails = re.findall(r'[\w\.-]+@[\w\.-]+', contact_info)
print(emails) # ['[email protected]', '[email protected]']
字符 | 功能说明 | 实际示例 |
---|---|---|
. | 匹配任意单字符 | a.c → “abc” |
\d | 匹配数字字符 | \d\d → “42” |
\w | 匹配单词字符 | \w+ → “Var123” |
\s | 匹配空白字符 | a\sb → “a b” |
量词 | 匹配规则 | 典型用例 |
---|---|---|
* | 零次或多次重复 | a*b → “b”, “aaaab” |
+ | 一次或多次重复 | a+b → “ab”, “aaaab” |
{n,m} | n到m次重复 | a{2,4}b → “aab”, “aaaab” |
log_entry = "2023-05-15 14:30:22 [ERROR] System crash"
match = re.match(r'(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2}) \[(\w+)\]', log_entry)
if match:
date, time, level = match.groups()
print(f"错误发生在{date} {time}, 级别:{level}")
html_content = "<p>第一段</p><p>第二段</p>"
# 贪婪模式
print(re.findall(r'<p>(.*)</p>', html_content))
# 非贪婪模式
print(re.findall(r'<p>(.*?)</p>', html_content))
# 提取后面跟着数字的Python
code_text = "Python3 Python2 Python"
print(re.findall(r'Python(?=\d)', code_text))
# 提取后面没有数字的Python
print(re.findall(r'Python(?!\d)', code_text))
contact_text = "办公室: 010-87654321, 手机: 13912345678"
phone_numbers = re.findall(r'\b\d{3}-\d{8}\b|\b1[3-9]\d{9}\b', contact_text)
print(phone_numbers) # ['010-87654321', '13912345678']
def check_password_strength(password):
"""验证密码是否包含大小写字母和数字,长度8-20位"""
pattern = r'^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[\w]{8,20}$'
return re.match(pattern, password) is not None
print(check_password_strength("Secure123")) # True
print(check_password_strength("weak")) # False
提升正则表达式效率:
re.compile()
预编译常用模式(?:...)
典型错误防范:
.
, *
,
+
, ?
需要正确转义
\u
匹配^[w\.-]+@[\w\.-]+\.\w+$
https?://[^\s]+
[\u4e00-\u9fa5]
\d{4}-\d{2}-\d{2}