搜索
首页后端开发Python教程Python正则表达式和re库的相关内容介绍(代码示例)

本篇文章给大家带来的内容是关于Python正则表达式和re库的相关内容介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。

正则表达式是定义搜索模式的字符序列。通常这种模式被字符串搜索算法用于字符串上的“查找”或“查找和替换”操作,或者用于输入验证。

1. 正则表达式的语法

  • . 表示任何单个字符

  • [] 字符集,对单个字符给出取值范围

  • [^] 非字符集,对单个字符给出排除范围

  • *前一个字符0次或者无限次扩展

  • +前一个字符1次或无限次扩展

  • ?前一个字符0次或1次扩展

  • |左右表达式任意一个

  • {m}扩展前一个字符m次

  • {m,n}扩展前一个字符m至n次

  • ^匹配字符串开头

  • $匹配字符串结尾

  • ()分组标记,内部只能使用|操作符

  • d数字,等价于[0-9]

  • w单词字符,等价于[A-Z,a-z,0-9]

2. python中re库的使用

Re库是python的标准库,主要用于字符串匹配,调用方法:import re

2.1. 正则表达式字符串的类型

re库采用raw string类型来表示正则表达式,表示为
r'text'
raw string是不包含对转义符的再次转义的字符串,总而言就是string会对字符转义,而raw string不会,因为在正则表达中会出现转义符号,所以避免繁琐我们使用raw string

2.2. Re库主要功能函数

  • re.search()在一个字符串中搜索正则表达式的第一个位置,返回match对象

  • re.match()从一个字符串的开始位置起匹配正则表达式,返回match对象

  • re.findall()搜索字符串,以列表类型返回全部能匹配的子串

  • re.split()将一个字符串按照正则表达式匹配结果进行分割,返回列表类型

  • re.finditer()搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象

  • re.sub()在一个字符串中替换所有匹配正则表达式的子串,返回替换后的字符串

2.2.1. re.search(pattern, string, flags=0)

在一个字符串中搜索正则表达式的第一个位置,返回match对象

  • pattern : 正则表达式的字符串或原生字符串表示

  • string : 待匹配字符串

  • flags : 正则表达式使用时的控制标记

  • re.I re.IGNORECASE 忽略正则表达式的大小写,[A‐Z]能够匹配小写字符

  • re.M re.MULTILINE 正则表达式中的^操作符能够将给定字符串的每行当作匹配开始

  • re.S re.DOTALL 正则表达式中的.操作符能够匹配所有字符,默认匹配除换行外的所有字符

举例说明:

import re
match = re.search(r'[1-9]\d{5}', 'BIT 100081')
if match:
    print(match.group(0))

结果为100081

2.2.2. re.match(pattern, string, flags=0)

从一个字符串的开始位置起匹配正则表达式,返回match对象
参数同search函数
举例说明:

import re
match = re.match(r'[1-9]\d{5}', 'BIT 100081')
print(match.group(0))

结果会报错,match为空,因为match函数是
从字符串开始位置开始匹配,因为从开始位置没有匹配到,所以为空

2.2.3. re.findall(pattern, string, flags=0)

搜索字符串,以列表类型返回全部能匹配的子串
参数同search
举例说明:

import re
ls=re.findall(r'[1-9]\d{5}', 'BIT100081 TSU100084')
print(ls)

结果为['100081', '100084']

2.2.4. re.split(pattern, string, maxsplit=0, flags=0)

将一个字符串按照正则表达式匹配结果进行分割返回列表类型

  • maxsplit : 最大分割数,剩余部分作为最后一个元素输出

举例说明 :

import re
re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084')
结果['BIT', ' TSU', ' ']
re.split(r'[1-9]\d{5}', 'BIT100081 TSU100084', maxsplit=1)
结果['BIT', ' TSU100081']

2.2.5. re.finditer(pattern, string, maxsplit=0, flags=0)

搜索字符串,返回一个匹配结果的迭代类型,每个迭代元素是match对象
参数同search
举例说明 :

import re
for m in re.finditer(r'[1-9]\d{5}', 'BIT100081 TSU100084'):
    if m:
        print(m.group(0))
结果为
100081
100084

2.2.6. re.sub(pattern, repl, string, count=0, flags=0)

在一个字符串中替换所有匹配正则表达式的子串返回替换后的字符串

  • repl : 替换匹配字符串的字符串

  • count : 匹配的最大替换次数

举例说明:

import re
re.sub(r'[1-9]\d{5}', ':zipcode', 'BIT100081 TSU100084')
结果为
'BIT:zipcode TSU:zipcode'

2.3 Re库的另一种等价用法(面向对象)

rst=re.search(r'[1-9]\d{5}', 'BIT 100081')
函数式的调用,一次性操作
pat=re.compile(r'[1-9]\d{5}')
rst=pat.search('BIT 100081')
编译后多次操作

regex=re.complie(pattern,flags=0)
regex也有以上六种用法

2.4 Re库的Match对象

Match对象是是一次匹配的结果,包含匹配的很多信息

以下是Match对象的属性

  • .string 待匹配的文本

  • .re 匹配时使用的patter对象(正则表达式)

  • .pos 正则表达式搜索文本的开始位置

  • .endpos 正则表达式搜索文本的结束位置

以下是Match对象的方法

  • .group(0) 获得匹配后的字符串

  • .start() 匹配字符串在原始字符串的开始位置

  • .end() 匹配字符串在原始字符串的结束位置

  • .span() 返回(.start(), .end())

2.5 Re库的贪婪匹配和最小匹配

当正则表达式可以匹配长短不同的多项时,返回哪一个呢?Re库默认采用贪婪匹配,即返回匹配最长的子串

最小匹配

  • *? 前一个字符0次或无限次扩展,最小匹配

  • +? 前一个字符1次或无限次扩展,最小匹配

  • ?? 前一个字符0次或1次扩展,最小匹配

  • {m,n}? 扩展前一个字符m至n次(含n),最小匹配

只要长度输出可能不同的,都可以通过在操作符后增加?变成最小匹配

以上是Python正则表达式和re库的相关内容介绍(代码示例)的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:segmentfault。如有侵权,请联系admin@php.cn删除
Python:深入研究汇编和解释Python:深入研究汇编和解释May 12, 2025 am 12:14 AM

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

Python是一种解释或编译语言,为什么重要?Python是一种解释或编译语言,为什么重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

对于python中的循环时循环与循环:解释了关键差异对于python中的循环时循环与循环:解释了关键差异May 12, 2025 am 12:08 AM

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

循环时:实用指南循环时:实用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解释吗?揭穿神话Python:它是真正的解释吗?揭穿神话May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

与同一元素的Python串联列表与同一元素的Python串联列表May 11, 2025 am 12:08 AM

concateNateListsinpythonwithTheSamelements,使用:1)operatototakeepduplicates,2)asettoremavelemavphicates,or3)listCompreanspearensionforcontroloverduplicates,每个methodhasdhasdifferentperferentperferentperforentperforentperforentperfortenceandordormplications。

解释与编译语言:Python的位置解释与编译语言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允许ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循环时:您什么时候在Python中使用?循环时:您什么时候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具