智慧產生和解釋正規表示式,支援各種常見模式比對
將您的文字指令轉換為公式,或輸入公式獲取解釋。
透過和 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}