python正则表达式练习题

1、匹配一个0-9之间任意数字

import re
s1="""1\n12\n995\n9999\n102\n02\n003\n4d"""
regex=re.compile('(?<![0-9])[0-9]{1,3}(?!\w)')
t=regex.findall(s1)
print(t)

在这里插入图片描述
2、匹配合法的ip地址
IP地址共有4位,每一位范围都是0-255

import re
s2="""192.168.1.150\n0.0.0.0\n255.255.255.255\n17.16.52.100\n172.16.0.100\n400.400.999.888\n001.022.003.000\n257.257.255.256"""
regex=re.compile('(((?:25[0-5])|(?:24[0-9])|(?:1\d{2})|(?:[0-9]{1,2}))\.){3}(((?:25[0-5])|(?:1\d{2})|(?:[0-9]{1,2})))')
t1=regex.finditer(s2)
for i in t1:
    print(s2[i.start():i.end()])

在这里插入图片描述
3、选出含有ftp的链接,且文件类型是gz或者xz的文件名

s3="""
ftp://ftp.astrom.com/pub/file/file-5.14.tar.gz
ftp://ftp.gmplib.org/pub/gmp-5.1.0/gmp-5.1.00tar.xz
ftp://ftp.vim,org/pub/vim/unix/vim-7.3.tar.ba2
http://anduin.linuxfromscratch.org/sources/LFS/lfs-packages/conglomeration//iana-etc/iana-etc-2.30.tar.bz2
http://anduin.linuxfromscratch.org/sources/other/udev-lfs-205-1.tar.bz2
http://download.savannah.gnu.org/releases/libpipeline/libpipeline-1.2.4.tar.gz
http://download.savannah.gnu.org/releases/man-db/man-db-2.6.5.tar,xz
http://download.savannah.gnu.org/releases/sysvinit/sysvinit-2.88dsf.tar.bz2
http://ftp.altlinux.org/pub/people/legion/kbd-1.15.5.tar.gz
http://mirror.hust.edu.cn/gnu/antoconf/autoconf-2.69.tar.gz
http://mirror.hust.edu.cn/gnu/antomake/automake-2.69.tar.gz
"""
import re
regex=re.compile('.ftp.*/(.*\.(?:gz|xz))')
t3=regex.finditer(s3)
for i in t3:
    print(s3[i.start():i.end()],'     分组             ',i.group(1))

这里用到了分组,需要注意的是只有re.Match object对象才能进行组的查询,findall返回一个列表,finditer返回一个迭代器
在这里插入图片描述
4、匹配邮箱

s4="""
test@hot-mail.com
v-ip@magedu.com
web.manager@magedu.com.cn
super.user@google.com
a@w-a-com
"""
import re 
regex=re.compile(".*@.*\.(?:(com)|(cn))")
t4=regex.finditer(s4)
for i in t4:
    print(s4[i.start():i.end()])

在这里插入图片描述
5、匹配URL

s5="""
http://www.magedu.com/index.html
https://login.magedu.com
file:///etc/sysconfig/network
"""
regex=re.compile('.*//(.*)')
t5=regex.findall(s5)
print(t5)

在这里插入图片描述

  • 3
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值