首页 > 编程语言 >Python正则表达式

Python正则表达式

时间:2023-04-13 22:37:18浏览次数:40  
标签:obj re Python group 正则表达式 print 匹配 match

1、re模块的介绍

在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用一个 re 模块
# 导入re模块
import re
# 使用match方法进行匹配操作
result = re.match(正则表达式,要匹配的字符串)
# 如果上一步匹配到数据的话,可以使用group方法来提取数据
result.group()

re.match() 根据正则表达式从头开始匹配字符串数据

2、re模块的使用

import re
# 使用match方法进行匹配操作
result = re.match("itcast","itcast.cn")
# 获取匹配结果
info = result.group()
print(info)

运行结果:
itcast

3、匹配单个字符

                                代码

功能

.

匹配任意1个字符(除了\n)

[ ]

匹配[ ]中列举的字符

\d

匹配数字,即0-9

\D

匹配非数字,即不是数字

\s

匹配空白,即 空格,tab键

\S

匹配非空白

\w

匹配非特殊字符,即a-z、A-Z、0-9、_、汉字

\W

匹配特殊字符,即非字母、非数字、非汉字

示例1: .

import re
ret = re.match(".","M")
print(ret.group())

ret = re.match("t.o","too")
print(ret.group())

ret = re.match("t.o","two")
print(ret.group())

运行结果:
M
too
two

示例2:[]

import re
# 如果hello的首字符小写,那么正则表达式需要小写的h
ret = re.match("h","hello Python") 
print(ret.group())
# 如果hello的首字符大写,那么正则表达式需要大写的H
ret = re.match("H","Hello Python") 
print(ret.group())
# 大小写h都可以的情况
ret = re.match("[hH]","hello Python")
print(ret.group())
ret = re.match("[hH]","Hello Python")
print(ret.group())
ret = re.match("[hH]ello Python","Hello Python")
print(ret.group())
# 匹配0到9第一种写法
ret = re.match("[0123456789]Hello Python","7Hello Python")
print(ret.group())
# 匹配0到9第二种写法
ret = re.match("[0-9]Hello Python","7Hello Python")
print(ret.group())
ret = re.match("[0-35-9]Hello Python","7Hello Python")
print(ret.group())
# 下面这个正则不能够匹配到数字4,因此ret为None
ret = re.match("[0-35-9]Hello Python","4Hello Python")
# print(ret.group())

运行结果:
h
H
h
H
Hello Python
7Hello Python
7Hello Python
7Hello Python

示例3:\d

import re

# 普通的匹配方式
ret = re.match("嫦娥1号","嫦娥1号发射成功") 
print(ret.group())

ret = re.match("嫦娥2号","嫦娥2号发射成功") 
print(ret.group())

ret = re.match("嫦娥3号","嫦娥3号发射成功") 
print(ret.group())

# 使用\d进行匹配
ret = re.match("嫦娥\d号","嫦娥1号发射成功") 
print(ret.group())

ret = re.match("嫦娥\d号","嫦娥2号发射成功") 
print(ret.group())

ret = re.match("嫦娥\d号","嫦娥3号发射成功") 
print(ret.group())
运行结果:

嫦娥1号
嫦娥2号
嫦娥3号
嫦娥1号
嫦娥2号
嫦娥3号

示例4:\D

import re

match_obj = re.match("\D", "f")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
f

示例5:\s

import re

# 空格属于空白字符
match_obj = re.match("hello\sworld", "hello world")
if match_obj:
    result = match_obj.group()
    print(result)
else:
    print("匹配失败")
# \t 属于空白字符
match_obj = re.match("hello\sworld", "hello\tworld")
if match_obj:
    result = match_obj.group()
    print(result)
else:
    print("匹配失败")
    
运行结果:
hello world
hello world

示例6:\S

import re

match_obj = re.match("hello\Sworld", "hello&world")
if match_obj:
result = match_obj.group()
print(result)
else:
print("匹配失败")
match_obj = re.match("hello\Sworld", "hello$world")
if match_obj:
result = match_obj.group()
print(result)
else:
print("匹配失败")

运行结果:
hello&world  
hello$world

示例7:\w

import re

# 匹配非特殊字符中的一位
match_obj = re.match("\w", "A")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
执行结果:
A

示例8:\W

# 匹配特殊字符中的一位
match_obj = re.match("\W", "&")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
执行结果:
&

4、匹配多个字符

代码

功能

*

匹配前一个字符出现0次或者无限次,即可有可无

+

匹配前一个字符出现1次或者无限次,即至少有1次

?

匹配前一个字符出现1次或者0次,即要么有1次,要么没有

{m}

匹配前一个字符出现m次

{m,n}

匹配前一个字符出现从m到n次

示例1:*

需求:匹配出一个字符串第一个字母为大小字符,后面都是小写字母并且这些小写字母可 有可无

import re

ret = re.match("[A-Z][a-z]*","M")
print(ret.group())

ret = re.match("[A-Z][a-z]*","MnnM")
print(ret.group())

ret = re.match("[A-Z][a-z]*","Aabcdef")
print(ret.group())

运行结果:
M
Mnn
Aabcdef

示例2:+

需求:匹配一个字符串,第一个字符是t,最后一个字符串是o,中间至少有一个字符

import re
match_obj = re.match("t.+o", "two")
if match_obj:
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
two

示例3:?

需求:匹配出这样的数据,但是https 这个s可能有,也可能是http 这个s没有

import re

match_obj = re.match("https?", "http")
if match_obj:
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
https

示例4:{m}、{m,n}

需求:匹配出,8到20位的密码,可以是大小写英文字母、数字、下划线

import re
ret = re.match("[a-zA-Z0-9_]{6}","12a3g45678")
print(ret.group())

ret = re.match("[a-zA-Z0-9_]{8,20}","1ad12f23s34455ff66")
print(ret.group())

运行结果:
12a3g4
1ad12f23s34455ff66

5、匹配开头和结尾

代码

功能

^

匹配字符串开头

$

匹配字符串结尾

示例1:^

需求:匹配以数字开头的数据

import re

# 匹配以数字开头的数据
match_obj = re.match("^\d.*", "3hello")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
3hello

示例2:$

需求: 匹配以数字结尾的数据

import re
# 匹配以数字结尾的数据
match_obj = re.match(".*\d$", "hello5")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
hello5

示例3:^ 和 $

需求: 匹配以数字开头中间内容不管以数字结尾

match_obj = re.match("^\d.*\d$", "4hello4")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
4hello4

6、除了指定字符以外都匹配

[^指定字符]: 表示除了指定字符都匹配

需求: 第一个字符除了aeiou的字符都匹配

import re
match_obj = re.match("[^aeiou]", "h")
if match_obj:
    # 获取匹配结果
    print(match_obj.group())
else:
    print("匹配失败")
    
执行结果
h

7、匹配分组

代码

功能

|

匹配左右任意一个表达式

(ab)

将括号中字符作为一个分组

\num

引用分组num匹配到的字符串

(?P<name>)

分组起别名

(?P=name)

引用别名为name分组匹配到的字符串

示例1:|

需求:在列表中["apple", "banana", "orange", "pear"],匹配apple和pear

import re

# 水果列表
fruit_list = ["apple", "banana", "orange", "pear"]

# 遍历数据
for value in fruit_list:
    # |    匹配左右任意一个表达式
    match_obj = re.match("apple|pear", value)
    if match_obj:
        print("%s是我想要的" % match_obj.group())
    else:
        print("%s不是我要的" % value)
        
执行结果:
apple是我想要的
banana不是我要的
orange不是我要的
pear是我想要的

示例2:( )

需求:匹配出163、126、qq等邮箱

import re

match_obj = re.match("[a-zA-Z0-9_]{4,20}@(163|126|qq|sina|yahoo)\.com", "[email protected]")
if match_obj:
    print(match_obj.group())
    # 获取分组数据
    print(match_obj.group(1))
else:
    print("匹配失败")
    
执行结果:
[email protected]
163

需求: 匹配qq:10567这样的数据,提取出来qq文字和qq号码

import re

match_obj = re.match("(qq):([1-9]\d{4,10})", "qq:10567")

if match_obj:
    print(match_obj.group())
    # 分组:默认是1一个分组,多个分组从左到右依次加1
    print(match_obj.group(1))
    # 提取第二个分组数据
    print(match_obj.group(2))
else:
    print("匹配失败")
    
执行结果:
qq
10567

示例3:\num

需求:匹配出<html>hh</html>

match_obj = re.match("<[a-zA-Z1-6]+>.*</[a-zA-Z1-6]+>", "<html>hh</div>")

if match_obj:
    print(match_obj.group())
else:
    print("匹配失败")

match_obj = re.match("<([a-zA-Z1-6]+)>.*</\\1>", "<html>hh</html>")

if match_obj:
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
<html>hh</div>
<html>hh</html>

需求:匹配出<html><h1>www.itcast.cn</h1></html>

match_obj = re.match("<([a-zA-Z1-6]+)><([a-zA-Z1-6]+)>.*</\\2></\\1>", "<html><h1>www.itcast.cn</h1></html>")

if match_obj:
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
<html><h1>www.itcast.cn</h1></html>

示例4:(?P<name>) (?P=name)

需求:匹配出<html><h1>www.itcast.cn</h1></html>

match_obj = re.match("<(?P<name1>[a-zA-Z1-6]+)><(?P<name2>[a-zA-Z1-6]+)>.*</(?P=name2)></(?P=name1)>", "<html><h1>www.itcast.cn</h1></html>")

if match_obj:
    print(match_obj.group())
else:
    print("匹配失败")
    
运行结果:
<html><h1>www.itcast.cn</h1></html>

标签:obj,re,Python,group,正则表达式,print,匹配,match
From: https://blog.51cto.com/u_13236892/6188451

相关文章

  • python爬虫基础
    下面是爬取网站源代码的代码,用的我们学校的教务处网站。。#!/usr/bin/envpythonimporturllibimporturllib2url='http://etc.sdut.edu.cn/eol/main.jsp'user_agent='Mozilla/5.0(X11;Ubuntu;Linuxx86_64;rv:42.0)Gecko/20100101Firefox/42.0'values={}values[......
  • python5:列表及其常用方法
    list(列表):是一个有序的集合,可以随时添加和删除其中的元素。特点:1:支持增删改查2:列表中的数据是可以变化的【数据项可以变化,内存地址不会改变】3:用[]来表示列表类型,数据项之间用逗号来分割,注意:数据项可以是任何类型的数据4:支持索引和切片来进行操作。 列表操作方法:append:在列......
  • python 离线安装包
    下载好第三方库,上传到服务器,用pip命令执行安装通过pypi官网下载包pypi官网提供各种Python的第三方库,主要提供Linux版本的后缀是".whl"和“.tar.gz”,可以搜索相关的包。".whl"文件离线安装(推荐)#以Markdown为例(默认文件在当前目录下)pipinstallMarkdown-3.2.2-py3-none-any.wh......
  • python 中英文对齐
    python中英文对齐代码defget_len(string:str):length=0forchinstring:if'\u4e00'<=ch<='\u9fa5':#是中文字符length+=2else:length+=1returnlengthdefaligned(string......
  • 基于pip的python包管理工具
    以下是软件下载链接:https://mysecreat.lanzoub.com/i5yvf0swgtne软件功能:可以对python包进行安装、卸载、升级、换源等操作,不用输入复杂命令源码:importosdefmenu():while(True):choice=input("1.安装2.卸载3.升级4.查看5.换源\n请输入:")if(choice==......
  • js正则表达式
    \d查找数字\D查找非数字字符\s查找空白字符\S查找非空白字符\w查找数字、字母及下划线\W查找非单词字符\n查找换行符\0查找NULL字符\r查找回车符n+查找一个或者多个如:/a+/匹配"candy"中的"a","caaaaaaandy"中所有的"a"当......
  • python面试题-2023(面试)
    1.python中有哪些可变类型与不可变类型?可变:list、dict、set不可变:tuple、str、整型(int、float、complex)注意:可变对象可以在原来地址上修改元素,不可变则不行(即不能在自己身上增删改),若要修改可以使用对象拼接赋值给新的对象,总之不能修改自身       参考链......
  • 跟着查老四学Python Day 8:面向对象编程
    面向对象编程基本概念日常寒暄之后,查老四开始讲课了查老四:好的,我会尽量满足你的要求。现在我们开始第一节:面向对象编程。面向对象编程(Object-OrientedProgramming,简称OOP)是一种编程范式,它提倡将现实世界中的事物抽象为程序中的类(Class)和对象(Object),通过封装(Encapsulation)、继承(Inhe......
  • 跟着查老四学Python Day 9:继承和多态
    继承例行寒暄之后,课程正式开始查老四:继承是面向对象编程中的一个重要概念。它允许我们创建一个新类,继承一个现有类的属性和方法,从而实现代码的重用。新类被称为子类,现有类被称为父类。在Python中,通过在子类名后的括号中写入父类名来实现继承。下面是一个简单的示例#父类classAni......
  • 跟着查老四学Python Day 11:类的高级特性
    学习类的特殊方法例行寒暄之后,查老四开始了几天的课程查老师:1.学习类的特殊方法,例如__init__、__str__、__repr__等Python中的类可以具有一些特殊方法,这些方法具有双下划线前缀和后缀,例如__init__、__str__和__repr__等。它们在特定情况下被自动调用。__init__:当创建类的实例时,会......