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

yipeiwu_com5年前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使用正则来处理各种匹配问题,希望对大家有所帮助!

相关文章

Python中使用双下划线防止类属性被覆盖问题

Python中使用双下划线防止类属性被覆盖问题

在使用Python编写面向对象的代码时,我们会常常使用“继承”这种开发方式。例如下面这一段代码: class Info: def __init__(self): pass...

新手该如何学python怎么学好python?

根据本人的学习经验,我总结了以下十点和大家分享: 1)学好python的第一步,就是马上到www.python.org网站上下载一个python版本。我建议初学者,不要下载具有IDE功能...

Python实现设置windows桌面壁纸代码分享

每天换一个壁纸,每天好心情。 # -*- coding: UTF-8 -*- from __future__ import unicode_literals import Ima...

详解python读取和输出到txt

详解python读取和输出到txt

读取txt的数据和把数据保存到txt中是经常要用到的,下面我就总结一下。 读txt文件 python常用的读取文件函数有三种read()、readline()、readlines()...

Python 自动安装 Rising 杀毒软件

不能使用时,或重新安装系统时,方便我们重新安装最新的版本. 但是每次安装都要点击好几次 Next 按钮,同时还要提供序列号,ID 等信息,我很讨厌这种重复工作,索性写一个小的脚本,让他自...