Python 正则表达式

article/2025/11/8 10:31:48

1.正则表达式的定义:

 正则表达式是对字符串进行解析(获取一大串字符串信息中,你想要的部分)。

 正则表达式是一种文本模式,模式描述在搜索文本时要匹配的一个或多个字符串。

 正则表达式,又成正规表示式,正规表示法,正规表达式,规则表达式,常规表示法(英语:Regular Expression,在代码 中常简写为regex、regexp或RE),是计算机科学的一个概念,正则表达式使用带个字符串来描述,匹配一系列匹配某个句 法规则的字符串,在很多文本编辑器里,正则表达式通常被用来检索,替换那些匹配某个模式的文本。

 Regular Expression的"Regular"一般被译为“正则”、“正规”、“常规”。此处的“Regular”即是“规则”、“规律”的意思,Regular Expression即“描述某种规则的表达式”之意。

2.正则表达式的作用和特点

作用:

1.给定的字符串是否符合正则表达式的过滤逻辑(称作“匹配”);
2.可以通过正则表达式,从字符串中获取我们想要的特定部分。

特点:

1.灵活性、逻辑性和功能性非常强。
2.可以迅速地用极简单的方式达到字符串的复杂控制。
3.对于刚接触的人来说,比较晦涩难懂。

常用知识点:

()是为了提取匹配的字符串。表达式中有几个()就有几个相应的匹配字符串。
[]是定义匹配的字符范围。比如 [a-zA-Z0-9] 表示相应位置的字符要匹配英文字符和数字。
{}一般用来表示匹配的长度,比如 \s{3} 表示匹配三个空格,\s{1,3}表示匹配一到三个空格。

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

实战练习理解

import remsg='sdfawerwedfsfsd'#1
pattern = re.compile('sdf')pattern.match(msg)result = pattern.match(msg)print(result)#2
#上面那个的封装版,只从开头进行匹配,若匹配不成功则返回None
print(re.match('sdf',msg)) #3
#search 进行正则字符串匹配方法,匹配的是整个字符串
result = re.search('we',msg)
print(result)#4
#返回位置
print(result.span())#a2b h6ks='qwec5wewe3bew2we'#search找到一个就停下来
result = re.search('[a-z][0-9][a-z]',s)
print(result.group())#msg='abcd7zjkfd8hdf00'#findall会一直找,直到匹配完
result = re.findall('[a-z][0-9][a-z]',s)
print(result)# 正则符号#a7a a88a a7878a
msg='a7aopa88ak jgkaa7878a'
# + 只要有1个或以上出现则符合 放在哪个后面就指哪个
result = re.findall('[a-z][0-9]+[a-z]',s)
print(result)#qq号码验证 5~11 开头不能为0
# ^从哪里开头 #从哪里结尾
msg='92351007388'
result = re.match('^[1-9][0-9]{5,11}$',msg)
print(result)#5
#用户名可以是字母或者数字,不能是数字开头,用户名长度必须在6位以上[0-9a-zA-Z]
username='s001adminda'
#第一位不能是数字 后面的只能是数字或字母 最后长度是5位以上 $以上述条件匹配到结尾
#result = re.match('[a-zA-Z][0-9a-zA-Z]{5,}$',username)
result = re.match('[a-zA-Z]\w{5,}$',username)
#result = re.search('[a-zA-Z][0-9a-zA-Z]{5,}$',username)
print(result)msg='aa.py bb.py cc.py kk.py'
result = re.findall(r'\w*\.py\b',msg)
print(result)'''
总结:.  任意字符 除了(\n)^  开头$  从头匹配到结尾要完全一样[] 范围正则预定义:
\s space 空白 (空格)
\b border 边界
\d digit 数字
\w word [0-9a-zA-Z_]大写反面 \S 非空格 \D 非数字...
'\w [0-9]' --> \w 和 [0-9] 只能匹配一个字母量词(跟在规则后面,表示字符串中一共有多少位沿用此规则) 举例:\w+  :
* 匹配前一个字符0次或无限次
+ 匹配前一个字符1次或无限次
? 匹配前一个字符0次或1次手机号码正则
re.match('1[35789]\d{9}$',phone){m}表示范围,有多少位 固定m位
{m, } 长度大于等于m
{m,n} 长度介乎m,n之间
'''#分组
#匹配数字0~100数字
n = '100'
#?前面可有可没有
#result = re.match('[1-9]?\d',n)
result = re.match(r'[1-9]?\d?$|100$',n)
print(result)#(word|word|word)这个表示一个单词 区别 [abc]这个表示一个字母例如如果是[163] 则表示要么是1 要么是6 要么是3
#验证输入的邮箱 163 126 qq
email = '923510073@qq2.com'
#最后加上$整体判断
result = re.match(r'\w{5,20}@(163|126|qq)\.(com|cn)$',email)
print(result)#不是以4.7结尾的手机号码(11位)
phone = '1590108867'
re.match(r'1\d{9}[0-35-689]$',phone)#爬虫
phone = '0110-12345679'
#小括号为分组 (010)分为一组 - (123456789)分为一组
result = re.match(r'(\d{3}|\d{4})-(\d{8}$)',phone)
print(result)
#分别提取
print(result.group(1))
print(result.group(2))#
msg1='<html>serwq</h2>'
msg='<h1>geeea</h1>'
# + 加号至少有一位 .任意一位
result = re.match(r'<[0-9a-zA-Z]+>(.+)</[0-9a-zA-Z]+>$',msg1)
print(result)
print(result.group(1))# \number  \引用第number个分组
result = re.match(r'<([0-9a-zA-Z]+)>(.+)</\1>$',msg)
print(result)
#print(result.group(1))msg3='<html><h1>ouou1</html></h1>'
result = re.match(r'<([0-9a-zA-Z]+)><([0-9a-zA-Z]+)>(.+)</\1></\2>$',msg3)
print(result)#起名的方式 (?P<名字>正则) (? P=名字)
msg='<html><h1>abc</h1></html>'
result = re.match(r'<(?P<name1>\w+)><(?P<name2>\w+)>(.+)</(?P=name2)></(?P=name1)>',msg)
print(result)
print(result.group(1))
print(result.group(2))
print(result.group(3))'''分组: () -->result.group(1) 获取组中匹配内容不需要引用分组的内容:result = re.match(r'<(?P<name1>\w+)><(?P<name2>\w+)>(.+)</(?P=name2)></(?P=name1)>',msg)print(result)print(result.group(1))引用分组匹配内容:1.number \number 引用第number组的数据msg='<html><h1>abc</h1></html>'result = re.match(r'<(?P<name1>\w+)><(?P<name2>\w+)>(.+)</(?P=name2)></(?P=name1)>',msg)print(result)2.?P<名字>re模块:match   从开头匹配一次search  只匹配一次findall 查找所有sub(正则表达式,'新内容','要被替换的内容')split result = re.split(r'[,:]','ouou1:123,ouou2:333')在字符串中搜索如果遇到 : 或者 , 就分割,将分割的内容保存在列表
'''result = re.sub(r'[a-z]+','100','ouou1:123,ouou2:333')
print(result)def func(temp):num = temp.group()#获取匹配到的字符串的值return str(int(num)+1)result = re.sub(r'\d+',func,'ouou1:123,ouou2:333')
print(result)result = re.split(r'[,:]','ouou1:123,ouou2:333')
print(result)#默认是贪婪的,只要后面有符合条件的则无限地往后取符合条件的
#例:abc1 已经符合条件 但是还是会往后取abc123
msg = 'abc123abc'
#result = re.match(r'abc(\d+)',msg)
result = re.match(r'abc(\d+?)',msg) # 加上?后,变成非贪婪
print(result)path = '<img src="https://static.oschina.net/uploads/img/201705/22114313_cGv0.png" style="width: 1007px;">'
result = re.search(r'src="(.*)"',path)
print(result.group(1))
import requests
response = requests.get(result.group(1))
with open('aa.png','wb')as wstream:wstream.write(response.content)

总结笔记:

'''
正则表达式:
re模块
import rere.match(pattern,str)
re.search(pattern,str)
re.findall(pattern,str)
re.sub()(pattern,'新的内容',str) 替换
re.split(pattern,str)   -->[]基础:
. 任意字符
[] 范围
| 或者
() 一组量词:
* >= 0
+ >= 1
? 0,1
{m} =m
{m,} >=m
{m,n}  >=m <=n预定义:
\s space
\S not space
\b border
\d digit
\D not digit
\w word[0-9a-zA-Z]
\W not word [^(0-9a-zA-Z)]分组:
() --> group(1)number(\w+)(\d*)  --> group(1) group(2)引用:(\w+)(\d*)    \1 \2  表示引用前面的内容name(?P<name>\w+)   (?P=name)Python里数量词默认是贪婪的(在少数语言里也可能是默认非贪婪),总是尝试匹配尽可能多的字符:非贪婪则相反,总是尝试匹配尽可能少的字符。在"*","?","+","{m,n}"后面加上? , 使贪婪变成非贪婪。
'''

re.py 中原文解释

'''r"""Support for regular expressions (RE).This module provides regular expression matching operations similar to
those found in Perl.  It supports both 8-bit and Unicode strings; both
the pattern and the strings being processed can contain null bytes and
characters outside the US ASCII range.Regular expressions can contain both special and ordinary characters.
Most ordinary characters, like "A", "a", or "0", are the simplest
regular expressions; they simply match themselves.  You can
concatenate ordinary characters, so last matches the string 'last'.The special characters are:"."      Matches any character except a newline."^"      Matches the start of the string."$"      Matches the end of the string or just before the newline atthe end of the string."*"      Matches 0 or more (greedy) repetitions of the preceding RE.Greedy means that it will match as many repetitions as possible."+"      Matches 1 or more (greedy) repetitions of the preceding RE."?"      Matches 0 or 1 (greedy) of the preceding RE.*?,+?,?? Non-greedy versions of the previous three special characters.{m,n}    Matches from m to n repetitions of the preceding RE.{m,n}?   Non-greedy version of the above."\\"     Either escapes special characters or signals a special sequence.[]       Indicates a set of characters.A "^" as the first character indicates a complementing set."|"      A|B, creates an RE that will match either A or B.(...)    Matches the RE inside the parentheses.The contents can be retrieved or matched later in the string.(?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below).(?:...)  Non-grouping version of regular parentheses.(?P<name>...) The substring matched by the group is accessible by name.(?P=name)     Matches the text matched earlier by the group named name.(?#...)  A comment; ignored.(?=...)  Matches if ... matches next, but doesn't consume the string.(?!...)  Matches if ... doesn't match next.(?<=...) Matches if preceded by ... (must be fixed length).(?<!...) Matches if not preceded by ... (must be fixed length).(?(id/name)yes|no) Matches yes pattern if the group with id/name matched,the (optional) no pattern otherwise.The special sequences consist of "\\" and a character from the list
below.  If the ordinary character is not on the list, then the
resulting RE will match the second character.\number  Matches the contents of the group of the same number.\A       Matches only at the start of the string.\Z       Matches only at the end of the string.\b       Matches the empty string, but only at the start or end of a word.\B       Matches the empty string, but not at the start or end of a word.\d       Matches any decimal digit; equivalent to the set [0-9] inbytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the wholerange of Unicode digits.\D       Matches any non-digit character; equivalent to [^\d].\s       Matches any whitespace character; equivalent to [ \t\n\r\f\v] inbytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match the wholerange of Unicode whitespace characters.\S       Matches any non-whitespace character; equivalent to [^\s].\w       Matches any alphanumeric character; equivalent to [a-zA-Z0-9_]in bytes patterns or string patterns with the ASCII flag.In string patterns without the ASCII flag, it will match therange of Unicode alphanumeric characters (letters plus digitsplus underscore).With LOCALE, it will match the set [0-9_] plus characters definedas letters for the current locale.\W       Matches the complement of \w.\\       Matches a literal backslash.This module exports the following functions:match     Match a regular expression pattern to the beginning of a string.fullmatch Match a regular expression pattern to all of a string.search    Search a string for the presence of a pattern.sub       Substitute occurrences of a pattern found in a string.subn      Same as sub, but also return the number of substitutions made.split     Split a string by the occurrences of a pattern.findall   Find all occurrences of a pattern in a string.finditer  Return an iterator yielding a Match object for each match.compile   Compile a pattern into a Pattern object.purge     Clear the regular expression cache.escape    Backslash all non-alphanumerics in a string.Some of the functions in this module takes flags as optional parameters:A  ASCII       For string patterns, make \w, \W, \b, \B, \d, \Dmatch the corresponding ASCII character categories(rather than the whole Unicode categories, which is thedefault).For bytes patterns, this flag is the only availablebehaviour and needn't be specified.I  IGNORECASE  Perform case-insensitive matching.L  LOCALE      Make \w, \W, \b, \B, dependent on the current locale.M  MULTILINE   "^" matches the beginning of lines (after a newline)as well as the string."$" matches the end of lines (before a newline) as wellas the end of the string.S  DOTALL      "." matches any character at all, including the newline.X  VERBOSE     Ignore whitespace and comments for nicer looking RE's.U  UNICODE     For compatibility only. Ignored for string patterns (itis the default), and forbidden for bytes patterns.This module also defines an exception 'error'."""

http://chatgpt.dhexx.cn/article/TBW5E1TQ.shtml

相关文章

python正则表达式详解

正则表达式是一个很强大的字符串处理工具&#xff0c;几乎任何关于字符串的操作都可以使用正则表达式来完成&#xff0c;作为一个爬虫工作者&#xff0c;每天和字符串打交道&#xff0c;正则表达式更是不可或缺的技能&#xff0c;正则表达式的在不同的语言中使用方式可能不一样…

详解Python正则表达式(含丰富案例)

前言&#xff1a;正则表达式在网络爬虫、数据分析中有着广泛使用&#xff0c;掌握正则表达式能够达到事半功倍的效果。本文详细介绍正则表达式中各种规则及其符号含义&#xff0c;并结合Python中的Re库进行演示&#xff0c;由浅入深&#xff0c;即学即练即用&#xff0c;内容丰…

Python超详细的正则表达式

目录 介绍 常用的正则表达式匹配规则表格 1.match() .group() 常用知识点 1.通用匹配 2.贪婪与非贪婪 3.修饰符 4.转义匹配 2.search() 3.findall() 4.sub() 总结 Hello大家好我是&#xff0c;PYmili&#xff01;今天给大家带来正则表达式的使用教程即匹配规则表格…

Python正则表达式(一看就懂)

目录 哈喽O(∩_∩)O&#x1f604; 什么是正则表达式(⊙_⊙) 简单说&#xff0c;正则表达式是… 正则表达式怎么用❓ sreach的用法&#x1f34a; 匹配连续的多个数值&#x1f349; 字符""重复前面一个匹配字符一次或者多次&#x1f349; 字符"*"重复前…

Python正则表达式详解 (超详细,看完必会!)

正则表达式详解 正则表达式 英文名称叫 Regular Expression简称RegEx&#xff0c;是用来匹配字符的一种工具&#xff0c;它常被用在网页爬虫&#xff0c;文稿整理&#xff0c;数据筛选等方面&#xff0c;最常用的就是用在网页爬虫&#xff0c;数据抓取。 一、正则表达式的各种…

Python 正则表达式详解(建议收藏!)

目录 match 匹配字符串 单字符匹配 . 匹配任意一个字符 \d 匹配数字 \D 匹配非数字 \s 匹配特殊字符&#xff0c;如空白&#xff0c;空格&#xff0c;tab等 \S 匹配非空白 \w 匹配单词、字符&#xff0c;如大小写字母&#xff0c;数字&#xff0c;_ 下划线 \W 匹配非…

Android工程中方法数超过65536解决方法(Kotlin)

Android Studio报错&#xff1a; The number of method references in a .dex file cannot exceed 64K. Caused by: com.android.tools.r8.utils.AbortException: Error: Cannot fit requested classes in a single dex file (# methods: 68815 > 65536) 解决方案 build.…

postman/EOLINKER测试报错 RangeError:Port should be 0 and 65536. Received 80892.

postman/EOLINKER测试报错 RangeError&#xff1a;Port should be > 0 and < 65536. Received 80892. RangeError&#xff1a;范围错误 RangeError是当一个只超出有效范围时发生的错误。主要的有几种情况&#xff0c;第一是数组长度为负数&#xff0c;第二是Number对象…

Android Studio Cannot fit requested classes in a single dex file (# methods: 72633 > 65536)解决办法

今天在Android Studio中构建Android工程时&#xff0c;出现了这样报错&#xff1a;“Cannot fit requested classes in a single dex file (# methods: 72633 &#xff1e; 65536)” 在网上找了一圈儿&#xff0c;总结个简单快速的解决方法 问题&#xff1a; Cannot fit req…

计算机端口号65536,65536端口能不能用

楼主asdd3000(asdd) 16位计算机端口65536个,32位计算机端口是65536/2个还是65536*2个?为什么? 问题点数:10、回复次数:20 Top 1 楼EvilOctal(冰血封情) 回复于 2004-04-08 20:41:04 得分 0 这个问题我真的不太清楚. 但是 好象和位数没关系吧? 服务端口是国际组织规定的,不是…

为什么89C51单片机里面有TH0=(65536-50000)/256;TL0=(65536-50000)%256;

由于89C51的晶振频率为12MHZ&#xff0c;机器周期是1us,则每1us产生一次计数&#xff0c;例如需要进行50ms的计时&#xff0c;对机器周期进行50000计数就可以得到&#xff0c;T0可以对机器周期进行65536次计数&#xff0c;为了不让T0溢出&#xff0c;我们需要对定时器/计数器赋…

NXP MCUXPresso - cc1plus.exe: out of memory allocating 65536 bytes

文章目录 NXP MCUXPresso - cc1plus.exe: out of memory allocating 65536 bytes概述实验结论补充END NXP MCUXPresso - cc1plus.exe: out of memory allocating 65536 bytes 概述 在尝试迁移 openpnp - Smoothieware project 从gcc命令行 MRI调试方式 到NXP MCUXpresso工程…

65536 65535 65534

65536 65535 65534 通常在导入模型的时候会遇到65534的限制&#xff0c;比如Unity里的“Meshes may not have more than 65534 vertices or triangles at the moment”提示。开起来像是2的16次方&#xff0c;但为什么不是65536&#xff1f;65536和65535会有什么问题&#xff1…

Eclipse中65536的解决办法

最近在做项目的时候&#xff0c;发现引入的第三方工程太多&#xff0c;无法打包成app文件了。如下 遇到这种问题怎么办呢&#xff1f;&#xff1f;&#xff1f;我们先看问题描述&#xff1a;方法数不在0-65536内&#xff0c;dalvik。。错误&#xff0c;不懂&#xff0c;还是先百…

Android中65536问题剖析

问题出现的原因是因为导入融云通信的包后&#xff0c;突然提示&#xff1a; Error:The number of method references in a .dex file cannot exceed 64K. Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html。 解决办法&#xf…

数据类型

强类型语言 强类型语言是一种强制类型定义的语言&#xff0c;一旦某一个变量被定义类型&#xff0c;如果不经过强制转换&#xff0c;则它永远就是该数据类型了&#xff0c;强类型语言包括Java、.net 、Python、C等语言&#xff0c;要求变量的使用要严格符合规定&#xff0c;所有…

C语言自己写代码实现的strcmp函数

我们在面试的时候&#xff0c;经常会被笔试实现C语言系统函数&#xff0c;比如strcmp函数&#xff0c;主要考察大家的C语言功底&#xff01; #include <assert.h> #include <stdio.h>int MyStrCmp(const char* str1, const char* str2) {assert((str1 ! NULL) &a…

用指针实现strcmp函数功能

strcmp函数的原理&#xff1a; 将两个字符串&#x1f50d;&#xff08;s1&#xff0c;s2&#xff09;的元素ascii码依次比较&#xff0c;直到遇到最短字符串的‘\0’&#xff0c;返回最后一个元素ascii码比较结果。 指针实现方式&#xff1a; 通过定义两个char*指针&#x1f5…

C语言中的strcmp函数的作用是什么,c语言strcmp函数用法是什么?

c语言strcmp函数用法&#xff1a;语法结构为【int strcmp(char *str1, char *str2)】&#xff0c;比较字符串str1和str2是否相同&#xff0c;如果相同则返回0&#xff0c;如果不同&#xff0c;在不同的字符处如果str1的字符大于str2字符&#xff0c;则返回负1。 c语言strcmp函数…

strcmp函数及模拟

strcmp包含在<string.h>的头文件中&#xff0c;作用是比较两个字符串。将 C 字符串 str1 与 C 字符串 str2 进行比较。 1.strcmp函数的参数和返回值、 参数&#xff1a;是两个待比较字符串的首地址 返回值&#xff1a;此函数开始比较每个字符串的第一个字符。如果它们彼此…