正则表达式实战
时间: 2023-06-29 12:21:04 浏览: 75
好的,关于正则表达式实战,我可以给你一些示例。
1. 匹配邮箱地址
```
import re
email = 'example@gmail.com'
if re.match(r'^\w+@\w+\.\w+$', email):
print('Valid email address')
else:
print('Invalid email address')
```
2. 匹配手机号码
```
import re
phone_number = '12345678901'
if re.match(r'^1[3456789]\d{9}$', phone_number):
print('Valid phone number')
else:
print('Invalid phone number')
```
3. 替换字符串中的特定字符
```
import re
text = 'Hello, World!'
new_text = re.sub(r'World', 'Python', text)
print(new_text)
```
4. 按照指定格式提取日期
```
import re
text = 'Today is 2021-07-01'
match = re.search(r'(\d{4})-(\d{2})-(\d{2})', text)
if match:
year, month, day = match.groups()
print(f'Today is {year}/{month}/{day}')
```
这些都是正则表达式的实际应用场景,希望对你有所帮助。