python使用正则来处理各种匹配问题

yipeiwu_com6年前Python基础

正则表达式是一个特殊的字符序列,它能帮助你方便的检查一个字符串是否与某种模式匹配。本文给大家介绍python使用正则来处理各种匹配问题,具体代码如下所述:

import re
##匹配列表内的非负整数
list = [99,100,-100,-1,90]
pattern = re.compile(r'[1-9]\d*|0')
for i in list:
    m = pattern.search(str(i))
    print(m)
##匹配列表内的整数
list = [99,100,-100,-1,90]
pattern = re.compile(r'[1-9]\d*')
for i in list:
    m = pattern.match(str(i))
    print(m)
##匹配列表内的非正整数
list = [99,100,-100,-1,90]
pattern = re.compile(r'-[1-9]\d*|0')
for i in list:
    m = pattern.match(str(i))
    print(m)
# ##正则匹配邮箱
c = re.compile(r'^\w+@(\w+\.)+(com|cn|net|edu)$')
string = '50772618@qq.com'
s = c.search(string)
if s:
  print(s.group())
##匹配十一位手机号
c = re.compile(r'^1[3-9]\d{9}$')
s = c.search('18785397892')
if s:
  print(s.group())
c = re.compile(r'^[1-9]\d*|0$')
s = c.search('')
if s:
  print(s.group())
##正则匹配日期
pattern = re.compile(r'[1-9]\d{3}-(1[0-2]|0?[1-9])-(3[0-1]|[1-2]\d|0?[1-9])')#定义匹配模式
string = 'hgfdjyjhfdjjj,2019-12-19jhgfjhgfjhf'
s = re.search(string)
print(s.group())
print(pattern.search(string,s.end()+1))
##匹配密码
pattern = re.compile(r'[A-Z]\w{7,9}')
m = pattern.search('basldaE3217894_324yiudasjl')
if m :
    print(m.group())

总结

以上所述是小编给大家介绍的python使用正则来处理各种匹配问题,希望对大家有所帮助!

相关文章

CentOS 6.5中安装Python 3.6.2的方法步骤

前言 centos 是自带python的。但是版本稍微旧一些。搞python开发,肯定要用新一点的稳定版。所以,要升级一下python。本文将介绍在CentOS 6.5中安装Python...

python栈的基本定义与使用方法示例【初始化、赋值、入栈、出栈等】

本文实例讲述了python栈的基本定义与使用方法。分享给大家供大家参考,具体如下: # -*- coding:utf-8 -*- #! python3 #在桟的设计中,我们需要定义一...

Python语言实现获取主机名根据端口杀死进程

推荐阅读:使用python检测主机存活端口及检查存活主机 下面给大家分享使用python语言实现获取主机名根据端口杀死进程代码。 ip=os.popen("ifconfig eth0...

Python静态类型检查新工具之pyright 使用指南

Python静态类型检查新工具之pyright 使用指南

Python是一门动态类型的语言,民间流传一种说法叫”动态一时爽,重构火葬场”,听起来够吓人的,好在这门语言在不断地改进,包括对 PEP484 引入的类型提示(Type Hint),就是...

Python中安装easy_install的方法

Python中安装easy_install的方法

easy_install是一个python的扩展包,主要是用来简化python安装第三方安装包,在安装了easy_install之后,安装python第三方安装包就只需要在命令行中输入:...