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实用技巧之列表、字典、集合中根据条件筛选数据详解

通用做法:迭代 以列表为例: 筛选出下列数字大于等于0的数 data = [2, 7, -4, -1, 3, 0, 8] res = [] for i in data: if i...

浅谈Python peewee 使用经验

本文使用案例是基于 python2.7 实现 以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作。所以,没有使用过 peewee,可以先阅读文档 正确性和覆盖面...

python正则匹配查询港澳通行证办理进度示例分享

复制代码 代码如下:import socketimport re '''广东省公安厅出入境政务服务网护照,通行证办理进度查询。分析网址格式为 http://www.gdcrj.com/w...

Python字典底层实现原理详解

在Python中,字典是通过散列表或说哈希表实现的。字典也被称为关联数组,还称为哈希数组等。也就是说,字典也是一个数组,但数组的索引是键经过哈希函数处理后得到的散列值。哈希函数的目的是使...

pow在python中的含义及用法

pow()方法返回xy(x的y次方) 的值 语法 以下是math模块pow()方法的语法: import math math.pow( x, y ) 内置的pow()方法 p...