正则表达式python用法
时间: 2023-10-30 12:05:32 浏览: 39
Python中正则表达式的用法可以通过re模块来实现。以下是一些常用的正则表达式Python用法示例:
1. 使用re.match()函数来匹配字符串的开头,如果匹配成功则返回一个匹配对象,否则返回None。
示例代码:
```python
import re
pattern = r'python'
string = 'python is a programming language'
result = re.match(pattern, string)
if result:
print("Match found!")
else:
print("Match not found.")
```
2. 使用re.search()函数来在字符串中搜索并返回第一个匹配的位置。如果匹配成功则返回一个匹配对象,否则返回None。
示例代码:
```python
import re
pattern = r'python'
string = 'I love Python programming'
result = re.search(pattern, string)
if result:
print("Match found at position:", result.start())
else:
print("Match not found.")
```
3. 使用re.findall()函数来在字符串中找到正则表达式所匹配的所有子串,并返回一个列表。如果没有找到匹配的,则返回空列表。
示例代码:
```python
import re
pattern = r'python'
string = '1python123python666python888'
result = re.findall(pattern, string)
print(result) # ['python', 'python', 'python']
```
4. 使用re.sub()函数来替换字符串中匹配正则表达式的部分。
示例代码:
```python
import re
pattern = r'python'
string = 'I love python programming'
new_string = re.sub(pattern, 'Java', string)
print(new_string) # I love Java programming
```
希望以上示例能帮助您理解和使用Python中的正则表达式。