在python中使用正则表达式

1.re模块介绍

1. re模块的使用过程

在Python中需要通过正则表达式对字符串进行匹配的时候,可以使用一个模块,名字为re

import re
# 使用match方法进行匹配操作
result = re.match(正则表达式,要匹配的字符串)
# 如果上一步匹配到数据的话,可以使用group方法来提取数据
result.group()

2. re模块示例

import re
result = re.match("itcast","itcast.cn")
result.group()

运行结果为:

itcast

3.re模块的高级用法

import re
string="worldpythonegcpythongg"
pattern=".python."
print(re.match(pattern,string))
print(re.search(pattern,string))
print(re.findall(pattern,string))
结果为:
None
<_sre.SRE_Match object; span=(4, 12), match='dpythone'>
['dpythone', 'cpythong']

match()函数是从内容的最开始位置开始匹配,如果匹配不到,就得到None
search()函数从全部内容匹配,如果有多个,找到第一个匹配的
findall()函数从全部内容匹配,如果有多个,找出所有匹配的


1.search

需求:匹配出水果的个数

import re

# 根据正则表达式查找数据,提示:只查找一次
# 1.pattern: 正则表达式
# 2.string: 要匹配的字符串
match_obj = re.search("\d+", "水果有20个 其中苹果10个")
if match_obj:
    # 获取匹配结果数据
    print(match_obj.group())
else:
    print("匹配失败")

运行结果:

20

2.findall

需求:匹配出多种水果的个数

import re


result = re.findall("\d+", "苹果10个 鸭梨5个 总共15个水果")
print(result)

运行结果:

['10', '5', '15']

3.sub

将匹配到的数据进行替换
re.sub(r'要替换的原字符','要替换的新字符','原始字符串')
eg:
re.sub(r'YOU','PYTHON','ILOVEYOU')
将原来的字符串’ILOVEYOU’里面的’YOU’替换成’PYTHON’

需求1:将匹配到的评论数改成22

import re

# pattern: 正则表达式
# repl: 替换后的字符串
# string: 要匹配的字符串
# count=0 替换次数,默认全部替换 , count=1根据指定次数替换
result = re.sub("\d+", "22", "评论数:10 赞数:20", count=1)
print(result)

运行结果:

评论数:22 赞数:20

需求2:将匹配到的阅读数加1

import re

# match_obj:该参数系统自动传入
def add(match_obj):
    # 获取匹配结果的数据
    value = match_obj.group()
    result = int(value) + 1
    # 返回值必须是字符串类型
    return str(result)

result = re.sub("\d+", add, "阅读数:10")
print(result)

运行结果:

阅读数:11

4.split

根据匹配进行切割字符串,并返回一个列表

需求:切割字符串"貂蝉,杨玉环:西施,王昭君"

import re
# 1. 正则
# 2. 要匹配的字符串
# maxsplit=1 分割次数, 默认全部分割
result = re.split(",|:", my_str, maxsplit=1)
print(result)

运行结果:

['貂蝉', '杨玉环:西施,王昭君']

5.re.complie

re模块中包含一个重要函数是compile(pattern [, flags]) ,该函数根据包含的正则表达式的字符串创建模式对象。可以实现更有效率的匹配。在直接使用字符串表示的正则表达式进行search,match和findall操作时,python会将字符串转换为正则表达式对象。而使用compile完成一次转换之后,在每次使用模式的时候就不用重复转换。当然,使用re.compile()函数进行转换后,re.search(pattern, string)的调用方式就转换为 pattern.search(string)的调用方式。

import re

# 简单使用就是在compile里面写正则的规则,在使用该对象去匹配
com = re.compile(r'\d+')                    # 用于匹配至少一个数字
m = com.findall('one12twothree34four')      # 需要匹配的对象
print(m)       # ['12', '34']

>>>import re
>>> pattern = re.compile(r'\d+')                    # 用于匹配至少一个数字
>>> m = pattern.match('one12twothree34four')        # 查找头部,没有匹配
>>> print m
None
>>> m = pattern.match('one12twothree34four', 2, 10) # 从'e'的位置开始匹配,没有匹配
>>> print m
None
>>> m = pattern.match('one12twothree34four', 3, 10) # 从'1'的位置开始匹配,正好匹配
>>> print m                                         # 返回一个 Match 对象
<_sre.SRE_Match object at 0x10a42aac0>
>>> m.group(0)   # 可省略 0
'12'
>>> m.start(0)   # 可省略 0
3
>>> m.end(0)     # 可省略 0
5
>>> m.span(0)    # 可省略 0
(3, 5)
>>>import re
>>> pattern = re.compile(r'([a-z]+) ([a-z]+)', re.I)   # re.I 表示忽略大小写
>>> m = pattern.match('Hello World Wide Web')
>>> print m                               # 匹配成功,返回一个 Match 对象
<_sre.SRE_Match object at 0x10bea83e8>
>>> m.group(0)                            # 返回匹配成功的整个子串
'Hello World'
>>> m.span(0)                             # 返回匹配成功的整个子串的索引
(0, 11)
>>> m.group(1)                            # 返回第一个分组匹配成功的子串
'Hello'
>>> m.span(1)                             # 返回第一个分组匹配成功的子串的索引
(0, 5)
>>> m.group(2)                            # 返回第二个分组匹配成功的子串
'World'
>>> m.span(2)                             # 返回第二个分组匹配成功的子串索引
(6, 11)
>>> m.groups()                            # 等价于 (m.group(1), m.group(2), ...)
('Hello', 'World')
>>> m.group(3)                            # 不存在第三个分组
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: no such group

2. 匹配单个字符

1.匹配规则

代码功能
.匹配任意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("匹配失败")

执行结果:

&

3.匹配多个字符

1. 匹配规则

代码功能
*匹配前一个字符出现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
# {a}表示前面的字符出现a次
ret = re.match("[a-zA-Z0-9_]{6}","12a3g45678")
print(ret.group())
#{a,b}表示前面的字符出现(a,b)次
ret = re.match("[a-zA-Z0-9_]{8,20}","1ad12f23s34455ff66")
print(ret.group())

运行结果:

12a3g4
1ad12f23s34455ff66

4.匹配开头,结尾,非

1. 匹配开头和结尾的正则表达式

代码功能
^匹配字符串开头
$匹配字符串结尾

示例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

2.除了指定字符以外都匹配

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

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

import re

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

执行结果

h

5.匹配分组

1. 匹配分组规则

代码功能
|匹配左右任意一个表达式
(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", "hello@163.com")
if match_obj:
    print(match_obj.group())
    # 获取分组数据
    print(match_obj.group(1))
else:
    print("匹配失败")

执行结果:

hello@163.com
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>

正则匹配所有邮箱:

import re  
text = input("Please input your Email address:\n")  
if re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$',text):  
#if re.match(r'[0-9a-zA-Z_]{0,19}@163.com',text):  
    print('Email address is Right!')  
else:  
    print('Please reset your right Email address!')

示例5 贪婪非贪婪

python里面正则表达式默认是贪婪的, 尽量根据正则表达式匹配数据

设置成为非贪婪, 非贪婪就是根据正则表达式尽量匹配数据

在"*","?","+","{m,n}"后面加上,使贪婪变成非贪婪。

 s="This is a number 234-235-22-423"
r=re.match(".+(\d+-\d+-\d+-\d+)",s)
r.group(1)
'4-235-22-423'    # 4前面的23被贪婪了

r=re.match(".+?(\d+-\d+-\d+-\d+)",s)  # 非贪婪
 r.group(1)
'234-235-22-423'

import re

my_str = """<img alt="小浅月o的直播" data-original="https://rpic.douyucdn.cn/live-cover/appCovers/2018/03/25/3544712_20180325111300_big.jpg" src="https://rpic.douyucdn.cn/live-cover/appCovers/2018/03/25/3544712_20180325111300_big.jpg" width="283" height="163" class="JS_listthumb" style="display: block;">"""

# python里面正则表达式默认是贪婪的, 尽量根据正则表达式多匹配数据
# 设置成为非贪婪, 非贪婪就是根据正则表达式尽量少匹配数据
# 非贪婪的样式: *? +? ??
# 非贪婪的含义:?后面的数据不要前面去匹配,让?后面匹配
match_obj = re.search(r"https?://.*?\.jpg", my_str)

if match_obj:
    # 获取匹配结果数据
    print(match_obj.group())
else:
    print("匹配失败")

#输出结果:
https://rpic.douyucdn.cn/live-cover/appCovers/2018/03/25/3544712_20180325111300_big.jpg

示例6 r的作用

Python中字符串前面加上 r 表示原生字符串,数据里面的反斜杠不需要进行转义,针对的只是反斜杠

Python里的原生字符串很好地解决了这个问题,有了原生字符串,你再也不用担心是不是漏写了反斜杠,写出来的表达式也更直观。

建议: 如果使用使用正则表达式匹配数据可以都加上r,要注意r针对的只是反斜杠起作用,不需要对其进行转义

>>> mm = "c:\\a\\b\\c"
>>> mm
'c:\\a\\b\\c'
>>> print(mm)
c:\a\b\c
>>> re.match("c:\\\\",mm).group()
'c:\\'
>>> ret = re.match("c:\\\\",mm).group()
>>> print(ret)
c:\
>>> ret = re.match("c:\\\\a",mm).group()
>>> print(ret)
c:\a
>>> ret = re.match(r"c:\\a",mm).group()
>>> print(ret)
c:\a
>>> ret = re.match(r"c:\a",mm).group()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'

正则匹配ip网段

re.findall(r"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?-(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$", "192.168.43.0-255")正则匹配ip网段

匹配邮箱

import re
def valid_email(email):
    re_email = re.compile(r'^[a-zA-Z\.]+@[a-zA-Z0-9]+\.[a-zA-Z]{3}$')
    if re_email.match(email):
        return 1
    else:
        return 0

校验密码

检验密码至少为数字、字母、下划线中的两种组合

    def invalid_password(password):
        # 检验密码至少为数字,字母,下划线中的两种
        p = re.compile(r'^(?![\d]+$)(?![a-zA-Z]+$)(?![\_]+$).{8,20}$')
        if not p.match(password):
            return False
        return True
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值