Python 正则表达式训练

正则表达式是处理文本的强大工具,Python通过re模块提供了正则表达式支持。下面是一些基础到进阶的正则表达式训练内容。

1. 基础匹配

import re

# 检查字符串是否包含"python"
text = "I love python programming"
pattern = r"python"
match = re.search(pattern, text)
if match:
    print("Found:", match.group())  # Found: python
 

2. 常用元字符

# \d 匹配数字
text = "My number is 123-456-7890"
pattern = r"\d{3}-\d{3}-\d{4}"
match = re.search(pattern, text)
print(match.group())  # 123-456-7890

# \w 匹配字母数字下划线
text = "User_name: john_doe123"
pattern = r"\w+"
matches = re.findall(pattern, text)
print(matches)  # ['User_name', 'john_doe123']

# . 匹配任意字符(除换行符)
text = "cat bat hat mat"
pattern = r".at"
matches = re.findall(pattern, text)
print(matches)  # ['cat', 'bat', 'hat', 'mat']
 

3. 字符集和量词

# [] 字符集
text = "The rain in Spain falls mainly in the plain"
pattern = r"[Ss]pain"
matches = re.findall(pattern, text)
print(matches)  # ['Spain', 'spain']

# 量词: *, +, ?, {n,m}
text = "color colour colooor"
pattern = r"colo[u]?r"  # ?表示前面的u出现0或1次
matches = re.findall(pattern, text)
print(matches)  # ['color', 'colour']

pattern = r"colo[u]+r"  # +表示前面的u出现1次或多次
matches = re.findall(pattern, text)
print(matches)  # ['colour', 'colouur']
 

4. 分组和捕获

# 分组提取
text = "John: 30, Jane: 25"
pattern = r"(\w+): (\d+)"
matches = re.findall(pattern, text)
for name, age in matches:
    print(f"{name} is {age} years old")
# John is 30 years old
# Jane is 25 years old

# 非捕获组 (?:...)
text = "hello world"
pattern = r"(?:hello|hi) world"
match = re.search(pattern, text)
print(match.group())  # hello world
 

5. 边界匹配

# ^ 字符串开头,$ 字符串结尾
text = "apple banana apple"
pattern = r"^apple"
match = re.search(pattern, text)
print(match.group())  # apple

pattern = r"apple$"
match = re.search(pattern, text)
print(match.group())  # apple

# \b 单词边界
text = "cat concatenate catfish"
pattern = r"\bcat\b"  # 只匹配单独的cat
matches = re.findall(pattern, text)
print(matches)  # ['cat']
 

6. 查找替换

# re.sub() 替换
text = "Today is 2023-05-15"
pattern = r"(\d{4})-(\d{2})-(\d{2})"
replacement = r"\2/\3/\1"  # 月/日/年
new_text = re.sub(pattern, replacement, text)
print(new_text)  # Today is 05/15/2023
 

7. 进阶练习

# 验证电子邮件
emails = ["test@example.com", "invalid@.com", "user.name@domain.co.uk"]
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
for email in emails:
    if re.match(pattern, email):
        print(f"{email} is valid")
    else:
        print(f"{email} is invalid")

# 提取HTML标签内容
html = "<h1>Title</h1><p>Paragraph 1</p><p>Paragraph 2</p>"
pattern = r"<[^>]+>(.*?)</[^>]+>"
matches = re.findall(pattern, html)
print(matches)  # ['Title', 'Paragraph 1', 'Paragraph 2']
 

8. 实用技巧

# 编译正则表达式(多次使用时提高效率)
pattern = re.compile(r"\b\w{4}\b")  # 匹配4字母单词
text = "This is a sample text with some words"
matches = pattern.findall(text)
print(matches)  # ['This', 'some', 'word']

# 忽略大小写匹配
text = "Python is awesome, PYTHON is powerful"
pattern = r"python"
matches = re.findall(pattern, text, flags=re.IGNORECASE)
print(matches)  # ['Python', 'PYTHON']

# 多行模式
text = """First line
Second line
Third line"""
pattern = r"^[A-Za-z]+"
matches = re.findall(pattern, text, flags=re.MULTILINE)
print(matches)  # ['First', 'Second', 'Third']
 

9. 复杂示例

# 解析日志文件
log = """
[2023-05-15 10:30:45] INFO: User 'admin' logged in
[2023-05-15 10:31:02] ERROR: Database connection failed
[2023-05-15 10:32:15] WARNING: Disk space low
"""

pattern = r"\[(.*?)\] (.*?): (.*)"
matches = re.findall(pattern, log)
for timestamp, level, message in matches:
    print(f"{timestamp} | {level:7} | {message}")

# 提取URL各部分
url = "https://www.example.com:8080/path/to/resource?query=string#fragment"
pattern = r"(https?)://([^/:]+)(?::(\d+))?(/[^?#]*)(?:\?([^#]*))?(?:#(.*))?"
match = re.match(pattern, url)
if match:
    protocol, domain, port, path, query, fragment = match.groups()
    print(f"Protocol: {protocol}")
    print(f"Domain: {domain}")
    print(f"Port: {port}")
    print(f"Path: {path}")
    print(f"Query: {query}")
    print(f"Fragment: {fragment}")
 

要掌握正则表达式,最重要的是多练习。可以从简单的模式开始,逐步构建更复杂的表达式。在线工具如 regex101.com 可以帮助你测试和调试正则表达式。

### 关于Python中的`pattern`正则表达式库 在Python中,虽然标准库提供了强大的`re`模块用于处理正则表达式[^1],但还有其他第三方库可以提供更高级的功能。其中,`pattern`是一个多功能的自然语言处理库,它不仅支持基本的字符串操作和正则匹配功能,还扩展了许多与文本分析、网络爬虫以及机器学习相关的特性。 #### `pattern`库简介 `pattern`库的主要目标是简化自然语言处理的任务。尽管它的核心功能并不完全专注于正则表达式的实现,但它确实包含了对正则表达式的支持,并将其与其他NLP工具集成在一起。以下是关于该库的一些重要信息: - **安装方式**: 使用pip命令可以直接安装此库: ```bash pip install pattern ``` - **主要用途**: - 文本挖掘与情感分析。 - HTML解析和网页抓取。 - 自然语言生成(NLG)。 - 正则表达式辅助函数。 #### 基础用法示例 下面展示如何利用`pattern.web`子模块来执行简单的HTML提取任务,同时结合正则表达式过滤数据。 ```python from pattern.web import URL, plaintext import re url = URL('https://example.com') html_content = url.download() # 将HTML转换为纯文本形式 text = plaintext(html_content) # 定义一个正则模式并查找所有符合条件的结果 matches = re.findall(r'\b\w{5}\b', text) # 查找长度为5的所有单词 print(matches) ``` 上述代码片段展示了通过`pattern.web.URL`获取远程资源的内容,并借助内置的`plaintext()`方法去除标签结构后应用自定义正则逻辑的过程[^2]。 #### 高级特性概述 除了基础的字符串匹配外,`pattern`还具备如下优势: - 支持多语言环境下的分词器(Tokenization)。 - 提供预训练模型来进行语法标注(Part-of-Speech Tagging)。 - 能够构建决策树分类器以解决特定领域内的预测问题。 值得注意的是,在某些情况下可能需要调整虚拟机参数或者配置文件才能顺利完成编译流程,尤其是在涉及移动开发场景下创建APK包时遇到兼容性错误的情况[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值