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

相关文章

django使用haystack调用Elasticsearch实现索引搜索

django使用haystack调用Elasticsearch实现索引搜索

前言: 在做一个商城项目的时候,需要实现商品搜索功能。 说到搜索,第一时间想到的是数据库的 select * from tb_sku where name like %苹果手机% 或者...

Python中一般处理中文的几种方法

Python中的中文是个很头痛的问题,Python2和Python3都会出现,而且py2中出现的概率要大些。  有一道面试题: Python中如何处理中文问题,能想到的就是以下...

python求最大连续子数组的和

抛出问题: 求一数组如 l = [0, 1, 2, 3, -4, 5, -6],求该数组的最大连续子数组的和 如结果为[0,1,2,3,-4,5] 的和为7 问题分析: 这个问题很...

python实现指定文件夹下的指定文件移动到指定位置

本文主要是写了一个将指定文件夹下的指定文件类型移动到指定位置,具体内容如下 # coding:utf-8 import os import shutil import sys rel...

Python中optparser库用法实例详解

本文研究的主要是Python中optparser库的相关内容,具体如下。 一直以来对optparser不是特别的理解,今天就狠下心,静下心研究了一下这个库。当然了,不敢说理解的很到位,但...