Python 正则表达式

正则表达式(Regular Expression)是一种强大的工具,用于在文本中搜索、匹配和替换特定模式的字符串。在 Python 中,可以使用 `re` 模块来操作正则表达式。下面是一些常见的正则表达式操作及相应的示例说明:

1. **匹配字符串**:
```python
import re

pattern = r"world"
text = "Hello, world! Welcome to the world."
matches = re.findall(pattern, text)
print(matches)
```

2. **使用元字符**:
```python
pattern = r"\b\w{5}\b"
text = "Python is a powerful programming language."
matches = re.findall(pattern, text)
print(matches)
```

3. **查找数字**:
```python
pattern = r"\d+"
text = "There are 123 apples and 456 oranges."
matches = re.findall(pattern, text)
print(matches)
```

4. **替换字符串**:
```python
pattern = r"apple"
text = "I like apple and banana."
replacement = "orange"
new_text = re.sub(pattern, replacement, text)
print(new_text)
```

5. **分割字符串**:
```python
pattern = r"\s+"
text = "Python is a high-level programming language."
parts = re.split(pattern, text)
print(parts)
```

6. **匹配邮件地址**:
```python
pattern = r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+"
text = "Contact us at email@example.com"
matches = re.findall(pattern, text)
print(matches)
```

7. **捕获组**:
```python
pattern = r"(\d{4})-(\d{2})-(\d{2})"
text = "Today's date is 2024-03-13."
matches = re.search(pattern, text)
if matches:
    year = matches.group(1)
    month = matches.group(2)
    day = matches.group(3)
    print(f"Year: {year}, Month: {month}, Day: {day}")
```

以上是一些常见的 Python 正则表达式操作示例,展示了如何使用正则表达式来匹配、搜索、替换字符串等操作。正则表达式可以帮助我们快速有效地处理文本数据,提取所需信息或进行字符串操作。

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值