Python 常用模块re

Python 常用模块re

【一】正则表达式

【1】说明

【2】字符组

  • 字符转使用[]表示,并在方括号内列出允许匹配的字符
  • 字符组中的字符之间的顺序没有特定意义,他们是等效的
  • 匹配字符组其中的任意一个字符
(1)常用字符组
正则–字符组 说明
[aeiou] 匹配任意一个小写元音字母
[0123456789] 匹配任意一个数字
[0-9] 匹配任意一个数字
[a-z] 匹配任意一个小写字母
[a-zA-Z] 匹配任意一个字母
[0-9a-zA-Z] 匹配任意一个字母或者数字

【3】元字符

  • 正则表达式中的元字符是具有特殊含义的字符,它们不仅仅匹配自身,还具有一些特殊的功能
(1)常用元字符
正则–元字符 说明
· 匹配任意一个除换行符(\n)以外的字符
要匹配包括“\n”在内的任何字符,请使用像“`(.
\w 匹配任意一个字母、数字或下划线
[A-Za-z0-9_]
\W 匹配任意一个非字母、数字或下划线
[^A-Za-z0-9_]
\s 匹配一个空白符(包括空格、制表符、换页符等)
[ \f\n\r\t\v]
\S 匹配一个非空白符(包括空格、制表符、换页符等)
[^ \f\n\r\t\v]
\d 匹配任意一个数字
[0-9]
\D 匹配任意一个非数字
[^0-9]
\t 匹配一个制表符
[\t]
\b 匹配一个单词的结尾
py\b可以匹配main.py的结尾py,但是不能匹配pythonpy
a|b 匹配字符a字符b
() 匹配括号内的表达式,也表示一个组
[…] 匹配字符组中的字符
[^…] 匹配除了字符组中字符的所有字符

【4】量词

  • 正则表达式中的量词用于指定一个模式中某个元素的匹配次数
(1)常用量词
正则–量词 说明
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次一次
{n} 重复n
{n,} 重复n次或更多次贪婪匹配优先匹配多次
{n,m} 重复n次m次贪婪匹配优先匹配m次
(2)非贪婪匹配
正则–量词 说明
{n,m}? 重复n次m次非贪婪匹配优先匹配n次

【5】位置

  • 正则表达式中的量词用于指定一个模式中某个元素的位置
(1)常用位置
正则–量词位置 说明
^ 匹配字符串的开始
$ 匹配字符串的结尾

【6】分组匹配

  • 在正则表达式中,分组是用小括号 () 括起来的部分,它允许你将一组字符当作一个单独的单元来处理

  • 例如 (abc){2,4} 表示匹配连续出现 2 到 4 次的 abc

【7】转义符

  • 在正则表达式中,转义字符用于取消字符的特殊含义,使其变成普通字符
  • 例如:在正则表达式中,. 表示匹配任意字符。如果你想匹配实际的点号,需要使用 \.

【8】模式修正符

  • 正则表达式的模式修正符是一种在正则表达式模式中添加修正标志以改变匹配规则的方式。修正标志通常以字母形式添加到正则表达式的末尾,用于调整匹配的方式
说明
re.I 是匹配对大小写不敏感
re.L 做本地化识别匹配
re.M 多行匹配,影响到^和$
re.S 使.匹配包括换行符在内的所有字符
re.U 根据Unicode字符集解析字符,影响\w、\W、\b、\B
re.X 通过给予我们功能灵活的格式以便更好的理解正则表达式
(1)re.S代码讲解
  • 使.匹配包括换行符在内的所有字符
  • 代码目的:匹配<>中的所有内容
    • 不使用模式修正符号,无法匹配到第二个<>
    • 使用模式修正符号,匹配到所有<>
import re

text = """
<age is 18>
<age is
18>
"""
pattern1 = re.compile(r"<.*>")
pattern2 = re.compile(r"<.*>", flags=re.S)
res = re.findall(pattern1, text)
print(res)
res = re.findall(pattern2, text)
print(res)

# ['<age is 18>']
# ['<age is 18>', '<age is\n18>']

【二】re模块

【1】编译正则表达式compile

  • 正则表达式编译之后会生成一个正则表达式对象,该对象可以被访问多次
  • 避免了在每次匹配时都重新解析正则表达式
re.compile(pattern, flags=0)

# pattern 	正则表达式
# flags		用于指定匹配模式修正符
import re

pattern = re.compile(r"\d")
print(pattern, type(pattern))
# re.compile('\\d') <class 're.Pattern'>

注意:模式修正符号
  • 使用编译方法时,修正符号必须放在编译方法里面,不能放在后续的使用方法中
import re

text = """
<age is 18>
<age is
18>
"""

# 正确
pattern1 = re.compile(r"<.*>", re.S)
print(pattern1)
res = re.findall(pattern1, text)
print(res)


# 错误
pattern1 = re.compile(r"<.*>")
print(pattern1)
res = re.findall(pattern1, text, re.S)
print(res)

【2】查找结果findall

  • 所有满足匹配结果的内容,返回一个列表
  • 避免了在每次匹配时都重新解析正则表达式
re.findall(pattern, string, flags=0)

# pattern 	正则表达式
# string 	待匹配字符串
# flags		用于指定匹配模式修正符
import re

pattern = re.compile(r"\w+")
text = "my name is bruce"
res = re.findall(pattern, text)
print(res)
# ['my', 'name', 'is', 'bruce']

注意:存在子组时
  • 将只返回子组内容

  • 需要使用非捕获分组(?:...)

import re

pattern = re.compile(r"\d+@(qq|163).com")
text = "15846354@qq.com"
res = re.findall(pattern, text)
print(res)
# ['qq']

pattern = re.compile(r"\d+@(?:qq|163).com")
text = "15846354@qq.com"
res = re.findall(pattern, text)
print(res)
# ['15846354@qq.com']

【3】查找结果search

  • 搜索第一个第一个第一个匹配成功的对象
  • 返回一个对象为空则返回None
  • 不像findall一样存在子组的问题
re.search(pattern, string, flags=0)

# pattern 	正则表达式
# string 	待匹配字符串
# flags		用于指定匹配模式修正符
注意:匹配对象的方法和属性
group()		# 匹配的结果字符串
start()		# 匹配成功的起始位置,从0开始
end()		# 匹配成功的结束位置,结束的后一个位置 
span()		# 元组形式,开始和结束位置
import re

pattern = re.compile(r"\d+")
text = "age is 18"
res = re.search(pattern, text)
print(res, type(res))                   # <re.Match object; span=(7, 9), match='18'> <class 're.Match'>
print(res.group())                      # 18
print(res.start())                      # 7
print(res.end())                        # 9
print(res.span(), type(res.span()))     # (7, 9) <class 'tuple'>

【3】查找结果match

  • match和search基本相同
  • 不同点:
    • match从字符串开头位置开始匹配
    • search在整个字符串中搜索第一个匹配结果
import re

pattern1 = re.compile(r"\w+")
pattern2 = re.compile(r"\d+")
text = "age is 18"
res = re.match(pattern1, text)
print(res)                      # <re.Match object; span=(0, 3), match='age'>
res = re.match(pattern2, text)
print(res)                      # None

【4】切割split

  • 用于根据正则表达式模式分割字符串
  • 返回一个由分割后的子字符串组成的列表
re.split(pattern, string, maxsplit=0, flags=0)

# pattern 	正则表达式
# string 	待匹配字符串
# maxsplit  指定最大分割次数,0表示不限制,从前往后开始切分
# flags		用于指定匹配模式修正符
import re

pattern = re.compile(r"\d+")
text = "aafa121ada021da12da"
res = re.split(pattern, text)
print(res)  # ['aafa', 'ada', 'da', 'da']
res = re.split(pattern, text, maxsplit=1)
print(res)  # ['aafa', 'ada021da12da']
注意:存在子组时
  • 子组的内容也将保留在列表中

  • 使用非捕获分组(?:...),将不会保存在列表中

import re

pattern = re.compile(r"(qq|163)")
text = "15846354@qq.com"
res = re.split(pattern, text)
print(res)
# ['15846354@', 'qq', '.com']

pattern = re.compile(r"(?:qq|163)")
text = "15846354@qq.com"
res = re.split(pattern, text)
print(res)
# ['15846354@', '.com']

【5】替换sub

  • 在字符串中替换正则表达式模式的匹配项, 默认替换
re.sub(pattern, repl, string, count=0, flags=0)

# pattern 	正则表达式
# repl  	替换匹配项的字符串或可调用对象
# string 	待匹配字符串
# count  	指定最大替换次数,0表示不限制,从前往后开始替换
# flags		用于指定匹配模式修正符
import re

pattern = re.compile(r"\d+")
text = "age is 18"
res = re.sub(pattern, "20", text)
print(res)
# age is 20
了解:repl是可调用对象
  • 将只返回子组内容

  • 需要使用非捕获分组(?:...)

import re

def to_upper(match):
    return match.group().upper()
text = "apple banana cherry date"
pattern = re.compile(r'\b\w{6}\b')  # 匹配长度为6的单词
result = pattern.sub(to_upper, text)
print(result)	# apple BANANA cherry date


def replace_adjacent(match):
    word = match.group()
    return f"{
     word} {
     word.upper()}"
text = "apple banana cherry date"
pattern = re.compile(r'\b\w{6}\b')  # 匹配长度为6的单词
result = pattern.sub(replace_adjacent, text)
print(result) 	# apple apple BANANA cherry date

【6】替换subn

  • sub和subn基本相同
  • 不同点:
    • sub返回替换后的字符串
    • sunb返回一个包含替换后的字符串和替换次数的元组
import re

pattern = re.compile(r"\d+")
text = "age is 18, money 50"
res = re.subn(pattern, "20", text)
print(res)
# ('age is 20, money 20', 2)

【7】切割finditer

  • 用于在字符串中查找正则表达式模式的所有匹配项
  • 返回一个迭代器
re.finditer(pattern, string, flags=0)

# pattern 	正则表达式
# string 	待匹配字符串
# flags		用于指定匹配模式修正符
import re

pattern = re.compile(r"\d+")
text = "age is 18, money 50"
res = re.finditer(pattern, text)
print(res, type(res))
for i in res:
    print(i)
# <callable_iterator object at 0x000002A4EC860D90> <class 'callable_iterator'>
# <re.Match object; span=(7, 9), match='18'>
# <re.Match object; span=(17, 19), match='50'>

【三】常用正则表达式

匹配内容 正则表达式
邮箱地址 ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
URL `^(https?
匹配日期(年-月-日) ^\d{4}-\d{2}-\d{2}$
匹配手机号码 ^1[3456789]\d{9}$
匹配身份证号码 ^\d{17}[\dXx]
IP 地址 `/((2[0-4]\d
匹配整数或浮点数 ^[-+]?[0-9]*\.?[0-9]+$
Unicode编码中的汉字范围 /^[\u2E80-\u9FFF]+$/

【四】练习

  • 获取金额,最小两位小数
import re


def get_money():
    while True:
        money = input("请输入金额(最小单位0.01):>>>").strip()
        pattern = re.compile(r"^\d+(\.\d{1,2})?$")
        res = re.match(pattern, money)
        if not res:
            print(f"输入内容{
     money}不合法,请输入")
            continue
        return money


print(get_money())

相关推荐

  1. Python 模块re

    2023-12-24 15:08:03       39 阅读
  2. Python模块

    2023-12-24 15:08:03       7 阅读
  3. Python 模块json

    2023-12-24 15:08:03       38 阅读
  4. Python 模块pickle

    2023-12-24 15:08:03       29 阅读
  5. python学习——re库的函数

    2023-12-24 15:08:03       10 阅读
  6. Python入门:模块—xml模块

    2023-12-24 15:08:03       26 阅读
  7. Pythonre模块

    2023-12-24 15:08:03       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2023-12-24 15:08:03       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2023-12-24 15:08:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2023-12-24 15:08:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2023-12-24 15:08:03       18 阅读

热门阅读

  1. k8s中的namespace及创建方式

    2023-12-24 15:08:03       36 阅读
  2. 单例模式的四种具体写法

    2023-12-24 15:08:03       41 阅读
  3. Python学习9

    2023-12-24 15:08:03       33 阅读
  4. Npm使用技巧

    2023-12-24 15:08:03       39 阅读
  5. 条形码数字识别的MATLAB仿真

    2023-12-24 15:08:03       35 阅读
  6. 测试理论知识八:敏捷开发测试、极限编程测试

    2023-12-24 15:08:03       42 阅读
  7. vue 通信方式

    2023-12-24 15:08:03       40 阅读
  8. MSF (Metasploit)基础

    2023-12-24 15:08:03       39 阅读