python 字符串正则表达式
时间: 2024-01-23 11:15:30 浏览: 23
在Python中,可以使用re模块来进行字符串的正则表达式操作。re模块提供了多个方法来匹配、搜索和提取满足特定规则的字符串。
下面是三个常用的re模块方法的介绍和示例:
1. match方法:从字符串的开头开始匹配,如果匹配成功,则返回一个匹配对象;如果匹配失败,则返回None。
```python
import re
pattern = r"hello"
string = "hello world"
result = re.match(pattern, string)
if result:
print("Match found!")
else:
print("Match not found!")
```
2. search方法:在字符串中搜索匹配的内容,如果匹配成功,则返回一个匹配对象;如果匹配失败,则返回None。search方法会在整个字符串中搜索,而不仅仅是从开头开始。
```python
import re
pattern = r"world"
string = "hello world"
result = re.search(pattern, string)
if result:
print("Match found!")
else:
print("Match not found!")
```
3. findall方法:在字符串中搜索匹配的内容,并返回所有匹配的结果作为一个列表。
```python
import re
pattern = r"\d+"
string = "I have 123 apples and 456 oranges"
result = re.findall(pattern, string)
print(result)
```