Python捕获分组
时间: 2024-04-20 17:21:00 浏览: 12
在Python中,捕获分组是正则表达式中的一种功能,用于从匹配的文本中提取特定部分。通过使用括号将要捕获的部分括起来,可以创建一个捕获分组。
以下是Python中捕获分组的一些常见用法:
1. 使用re模块的search()函数进行捕获分组:
```python
import re
pattern = r"(\d{3})-(\d{4})"
text = "电话号码是:123-4567"
match = re.search(pattern, text)
if match:
area_code = match.group(1)
phone_number = match.group(2)
print("区号:", area_code)
print("电话号码:", phone_number)
```
2. 使用re模块的findall()函数进行多个捕获分组的提取:
```python
import re
pattern = r"(\w+)\s(\w+)"
text = "Hello World"
matches = re.findall(pattern, text)
for match in matches:
first_name = match
last_name = match
print("名字:", first_name)
print("姓氏:", last_name)
```
3. 使用re模块的sub()函数进行替换和捕获分组的提取:
```python
import re
pattern = r"(\w+)\s(\w+)"
text = "Hello World"
new_text = re.sub(pattern, r"\2, \1", text)
print(new_text) # 输出:World, Hello
```