Python正则表达式实战指南:从基础匹配到高级技巧
本文详细介绍Python中re模块的使用,涵盖compile创建正则对象、search与findall匹配方法、括号分组、管道符多选、可选及重复量词(*、+、{n})的应用,以及贪心与非贪心匹配、自定义字符集、边界锚点和通配符等核心技巧,助力自动化文本处理。
一、创建正则表达式
1. re模块基础
Python的所有正则表达式功能均封装在re模块中,使用前需先导入该模块。
import rere模块提供的compile()函数用于构建正则表达式对象。向compile()传入表示正则规则的字符串,该函数将返回一个Regex模式对象,后续操作均基于此对象进行。
2. 匹配Regex对象
Regex对象提供的search()方法用于在目标字符串中查找匹配项。若未找到匹配内容,该方法返回None;若找到匹配,则返回一个Match对象。通过调用Match对象的group()方法,可以获取具体的匹配结果字符串。
import re
ageRegex=re.compile(r'\d\d\d\d')
a=ageRegex.search("今年是2023年")
print(a)
print(a.group())
'''<re.Match object; span=(3, 7), match='2023'>
2023
'''二、正则表达式匹配更多模式
1. 利用括号进行分组
在compile()传入的字符串中,使用括号可以将匹配内容划分为不同的组。通过Match对象的group(index)方法并指定下标,可以分别查看各组匹配结果;若需查看所有分组数据,可使用groups()方法。
import re
Regex=re.compile(r'(\d\d\d\d)-(\d)-(\d)')
a=Regex.search('今年是2023-1-1')
print(a)
print(a.group(1))
print(a.groups())
'''<re.Match object; span=(3, 11), match='2023-1-1'>
2023
('2023', '1', '1')
'''2. 使用管道符匹配多个分组
符号|被称为管道符,用于连接多个字符串以实现“或”匹配。例如A|B可匹配A或B。若字符串中同时存在A和B,search()仅将最先出现的匹配项放入Match对象中。
import re
Regex=re.compile(r'hello|hi')
a=Regex.search('hello world hi time')
print(a.group())
'''hello'''同样可以通过括号将多个匹配数据分组,使用group()查看整体匹配,而group(1)则专门用于查看通过管道符匹配到的具体子组数据。
import re
Regex=re.compile(r'Bat(man|mobile|bat)')
a=Regex.search('Batmobile lost a wheel , l like Batman')
print(a.group())
print(a.group(1))
'''Batmobile
mobile'''3. 使用问号表示可选匹配
当某部分数据可能存在也可能不存在时,可使用问号?来实现可选匹配。
import re
Regex=re.compile(r'hello (world)?')
a=Regex.search('hello world hello time')
b=Regex.search('hello time')
print(a.group())
print(b.group())
'''hello world
hello '''即使字符串中不包含可选部分,只要其他部分匹配成功,整体匹配依然有效,不会因缺少可选数据而影响结果。
4. 使用星号匹配零次或多次
星号*表示前面的元素出现零次或多次,即被星号修饰的内容可以出现一次、多次或不出现。
import re
Regex=re.compile(r'(super)*man')
a=Regex.search('I am superman')
b=Regex.search('I am supersupersuperman')
print(a.group())
print(b.group())
'''superman
supersupersuperman
'''5. 使用加号表示匹配一次或多次
与星号不同,加号+表示前面的元素必须出现至少一次。若未找到任何匹配,返回的Match对象将为None。
import re
Regex=re.compile(r'(super)+man')
c=Regex.search('I am man')
a=Regex.search('I am superman')
b=Regex.search('I am supersupersuperman')
print(a.group())
print(b.group())
print(c)
'''superman
supersupersuperman
None
'''6. 使用花括号匹配特定次数
(a){3}表示精确匹配字符串'aaa',但不匹配'aa'。若花括号内包含两个数,如(a){3,5},则表示匹配次数在最小值到最大值之间,例如匹配'aaa'、'aaaa'或'aaaaa'。花括号中的最小值或最大值也可以省略。
import re
Regex=re.compile(r'(hello){2}')
a=Regex.search('hellohello time hello')
print(a.group())
'''hellohello'''三、贪心和非贪心匹配
Python的正则表达式默认采用贪心匹配模式,即在存在多种可能时,默认匹配最长的字符串。若希望正则表达式不采用贪心模式,可在花括号后添加一个问号?来限制匹配长度,使其变为非贪心匹配。
import re
Regex=re.compile(r'(a){2,8}?')
Regex1=re.compile(r'(a){2,8}')
string='aaaaaaaaaaaaaa'
a=Regex.search(string)
b=Regex1.search(string)
print(a.group()) #非贪心
print(b.group())
'''aa
aaaaaaaa'''findall()方法
search()方法返回第一个匹配字符串对应的Match对象,而findall()方法功能类似但更为强大。findall()可以找出所有匹配项:若只找到一个匹配,则返回该字符串;若找到多个匹配,则返回一个包含所有匹配字符串的列表(原文称元组,实际Python中为列表)。
import re
Regex=re.compile(r'hello')
string='hello world! hello time!'
a=Regex.search(string)
b=Regex.findall(string)
print(a.group())
print(b)
'''hello
['hello', 'hello']'''四、字符分类
| 缩写字符串分类 | 表示 |
| \d | 0到9的任何数字 |
| \D | 除0到9以外的任意字符 |
| \w | 字母,数字或下划线字符 |
| \W | 除字母,数字和下划线外的任意字符 |
| \s | 空格,制表符或换行符 |
| \S | 除空格,制表符和换行符外的任意字符 |
常用字符分类包括:\d+匹配一次或多次数字,\s匹配空格、制表符或换行符,\w+匹配字母、数字或下划线。
import re
Regex=re.compile(r'\d+\s\w+')
a=Regex.findall('1 dog,2 pig,3 duck,4 cat,5 fish,6 col')
print(a)
'''['1 dog', '2 pig', '3 duck', '4 cat', '5 fish', '6 col']'''五、自定义字符分类
1. 创建自定义字符集
通过方括号内的连字符-可以创建自定义字符集。例如[a-z]匹配a到z的小写字母,[A-Z0-9]匹配A到Z的大写字母或0到9的数字。若在方括号内加上^符号,表示不匹配这些字符,例如[^a-z]表示不匹配a到z的小写字母,[aiuoe]则表示匹配指定的元音字母。
import re
Regex=re.compile(r'[a-z]')
Regex1=re.compile(r'[aioue]') #元音
string='abcdefghijklmnopqrstuvwsyz'
a=Regex.findall(string)
b=Regex1.findall(string)
print(b)
'''['a', 'e', 'i', 'o', 'u']'''
print(a)
'''['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 's', 'y', 'z']'''2. 插入符号和美元符号
插入符号^表示匹配字符串的起始位置,美元符号$表示匹配字符串的结束位置。例如^\d表示从0到9的数字开始匹配,\d$表示匹配以0到9数字结尾的字符串。
import re
Regex=re.compile(r'^\d+\w+$')
a=Regex.findall('1b32c23d')
print(a)
'''['1b32c23d']'''3. 通配字符
点号.表示通配符,它可以匹配除换行符以外的所有字符。
import re
Regex=re.compile(r'.a.')
a=Regex.findall('dfweascareaefefwa')
print(a)
'''['eas', 'car', 'eae']'''4. 使用(.*)匹配所有字符
(.*)用于匹配所有字符,其中.匹配除换行符外的所有字符,*表示出现零次或多次。
import re
Regex=re.compile(r'<.*>')
a=Regex.findall('<adf>,<fedf>,<gre>,<fww2>')
print(a)
'''['<adf>,<fedf>,<gre>,<fww2>']'''5. 使用参数re.DOTALL匹配换行
在compile()函数中,通过传入re.DOTALL作为第二个参数,可以使通配符.匹配所有字符,包括换行符。
import re
Regex=re.compile(r'.*',re.DOTALL)
a=Regex.findall('hello world hello time')
print(a)
'''['hello world hello time', '']'''至此,关于Python正则表达式实现自动化编程的介绍已完成。如需了解更多Python正则表达式相关内容,可搜索本站历史文章或继续浏览后续相关文章,感谢支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













