python 正则表达式习题

本文通过一系列习题介绍了Python正则表达式的应用,包括匹配数字、IP地址、FTP链接、邮箱地址、HTML标签、URL、中国二代身份证号,以及密码强度的正则匹配方法。通过这些实例,读者可以深入理解Python正则表达式的使用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.匹配0到999任意数字:
在这里插入图片描述
import re

L = [‘1’,‘12’,‘995’,‘9999’,‘102’,‘02’,‘003’,‘4d’]
for i in L:
print(re.match(r’\b\d{1,3}\b’,i))
输出
2.匹配合法的IP地址
在这里插入图片描述
import re

L = [‘192.168.1.150’,‘0.0.0.0’,‘255.255.255.255’,‘17.16.52.100’,‘172.16.0.100’,‘400.400.999.888’,‘001.022.003.000’,‘257.257.255.256’]
for i in L:
print(re.match(r’(\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\b.){3}(\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-5][0-5])\b)’,i))
输出

3.选出含有ftp的链接

1. 匹配以hello开头的字符串。 ```python import re pattern = "^hello" string = "hello world" result = re.match(pattern, string) if result: print("Matched") else: print("Not matched") ``` 2. 匹配以world结尾的字符串。 ```python import re pattern = "world$" string = "hello world" result = re.search(pattern, string) if result: print("Matched") else: print("Not matched") ``` 3. 匹配包含数字的字符串。 ```python import re pattern = "\d+" string = "abc123def456" result = re.findall(pattern, string) print(result) ``` 4. 匹配只包含数字的字符串。 ```python import re pattern = "^\d+$" string = "123456" result = re.match(pattern, string) if result: print("Matched") else: print("Not matched") ``` 5. 匹配包含字母和数字的字符串。 ```python import re pattern = "[a-zA-Z0-9]+" string = "abc123def456" result = re.findall(pattern, string) print(result) ``` 6. 匹配只包含字母和数字的字符串。 ```python import re pattern = "^[a-zA-Z0-9]+$" string = "abc123" result = re.match(pattern, string) if result: print("Matched") else: print("Not matched") ``` 7. 匹配包含特殊字符的字符串。 ```python import re pattern = "[^a-zA-Z0-9\s]+" string = "abc!@#def$%^" result = re.findall(pattern, string) print(result) ``` 8. 匹配只包含特殊字符的字符串。 ```python import re pattern = "^[^a-zA-Z0-9\s]+$" string = "!@#$%^&*()" result = re.match(pattern, string) if result: print("Matched") else: print("Not matched") ``` 9. 匹配邮箱地址。 ```python import re pattern = "^\w+@\w+\.\w+$" string = "example@gmail.com" result = re.match(pattern, string) if result: print("Matched") else: print("Not matched") ``` 10. 匹配手机号码。 ```python import re pattern = "^1[3-9]\d{9}$" string = "13812345678" result = re.match(pattern, string) if result: print("Matched") else: print("Not matched") ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值