Python的re模块

本文介绍了Python使用re模块处理正则表达式的能力。涵盖了正则表达式的常量,如re.M、re.S等;编译方法,如re.compile;匹配方法,如re.match、re.search等;全文搜索方法,如re.finditer、re.findall;替换和分割方法,以及分组的使用,包括普通分组和命名分组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python的正则表达式

Python使用re模块提供了正则表达式处理的能力。 常量

常量

re.M

re.MULTILINE

re.S

re.DOTALL

re.I

re.IGNORECASE

re.X

re.VERBOSE

使用 | 位或 运算开启多种选项 方法

编译

re.compile(pattern, flags=0)

说明

多行模式

单行模式

忽略大小写

忽略表达式中的空白字符

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


regex.search(string[, pos[, endpos]])

for i,c in enumerate(s, 1):

print((i-1, c), end=’\n’ if i%10==0 else ’ ')

print()

(0, ‘b’)(1, ‘o’)(2, ‘t’)(3, ‘t’)(4, ‘l’)(5, ‘e’)(6, ‘\n’)(7, ‘b’)(8, ‘a’)(9, ‘g’)

(10, ‘\n’)(11, ‘b’)(12, ‘i’)(13, ‘g’)(14, ‘\x07’)(15, ‘p’)(16, ‘p’)(17, ‘l’)(18, ‘e’) # match方法

print(’–match–’)

result = re.match(‘b’, s) # 找到一个就不找了

print(1, result) # bottle

result = re.match(‘a’, s) # 没找到,返回None

print(2, result)

result = re.match(’^a’, s, re.M) # 依然从头开始找,多行模式没有用

print(3, result)

result = re.match(’^a’, s, re.S) # 依然从头开始找

print(4, result)

# 先编译,然后使用正则表达式对象

regex = re.compile(‘a’)

result = regex.match(s) # 依然从头开始找

print(5, result)

result = regex.match(s, 15) # 把索引15作为开始找

print(6, result) # apple

print()

# search方法

print(’–search–’)

result = re.search(‘a’, s) # 扫描找到匹配的第一个位置

print(7, result) # apple

regex = re.compile(‘b’)

result = regex.search(s, 1)

print(8, result) # bag

regex = re.compile(’^b’, re.M)

result = regex.search(s) # 不管是不是多行,找到就返回

print(8.5, result) # bottle

result = regex.search(s, 8)

print(9, result) # big

# fullmatch方法

result = re.fullmatch(‘bag’, s)

print(10, result)

regex = re.compile(‘bag’)

result = regex.fullmatch(s)

print(11, result)

result = regex.fullmatch(s, 7)

print(12, result)

result = regex.fullmatch(s, 7, 10)

print(13, result) # 要完全匹配,多了少了都不行, [7, 10)

全文搜索

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


regex.finditer(string[, pos[, endpos]])

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


regex.findall(string[, pos[, endpos]])

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


regex.sub(replacement, string, count=0)

re.subn(pattern, replacement, string, count=0, flags=0)


regex.subn(replacement, string, count=0)

同sub返回一个元组(new_string, number_of_subs_made)

import re

s = ‘’‘bottle\nbag\nbig\napple’’'

for i,c in enumerate(s, 1):

print((i-1, c), end=’\n’ if i%8==0 else ’ ')

print()

(0, ‘b’) (1, ‘o’) (2, ‘t’) (3, ‘t’) (4, ‘l’) (5, ‘e’) (6, ‘\n’) (7, ‘b’) (8, ‘a’) (9, ‘g’) (10, ‘\n’)(11, ‘b’)(12, ‘i’)(13, ‘g’)(14, ‘\n’)(15, ‘a’)(16, ‘p’)(17, ‘p’)(18, ‘l’)(19, ‘e’)

# 替换方法

regex = re.compile(‘b\wg’)

result = regex.sub(‘magedu’, s)

print(1, result) # 被替换后的字符串

result = regex.sub(‘magedu’, s, 1) # 替换1次

print(2, result) # 被替换后的字符串

regex = re.compile(’\s+’)

result = regex.subn(’\t’, s)

print(3, result) # 被替换后的字符串及替换次数的元组

分割字符串

字符串的分割函数split,太难用,不能指定多个字符进行分割。

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

re.split分割字符串

import re

s = “”"

os.path.abspath(path)

normpath(join(os.getcwd(), path)).

"""

# 把每行单词提取出来

print(s.split())

# 做不到[‘os.path.abspath(path)’, ‘normpath(join(os.getcwd(),’, ‘path)).’]

print(re.split(’[\.()\s,]+’, s))

分组

使用小括号的pattern捕获的数据被放到了组group中。

match、search函数可以返回match对象;findall返回字符串列表;finditer返回一个个match对象 如果pattern中使用了分组,如果有匹配的结果,会在match对象中

1. 使用group(N)方式返回对应分组,1到N是对应的分组,0返回整个匹配的字符串,N不写缺省为0

2. 如果使用了命名分组,可以使用group(‘name’)的方式取分组

3. 也可以使用groups()返回所有组

4. 使用groupdict() 返回所有命名的分组

import re

s = ‘’‘bottle\nbag\nbig\napple’’'

for i,c in enumerate(s, 1):

print((i-1, c), end=’\n’ if i%10==0 else ’ ')

print()

# 分组

regex = re.compile(’(b\w+)’)

result = regex.match(s) # 从头匹配一次

print(type(result))

print(1, ‘match’, result.groups())

result = regex.search(s, 1) # 从指定位置向后匹配一次

print(2, ‘search’, result.groups()) #

# 命名分组

regex = re.compile(’(b\w+)\n(?P<name2>b\w+)\n(?P<name3>b\w+)’) result = regex.match(s)

print(3, ‘match’, result)

print(4, result.group(3), result.group(2), result.group(1)) print(5, result.group(0).encode()) # 0 返回整个匹配字符串,即match print(6, result.group(‘name2’), result.group(‘name3’)) print(6, result.groups())

print(7, result.groupdict())

result = regex.findall(s) # 返回什么,有几项?

for x in result: # 有分组里面放的东西不一样

print(type(x), x)

regex = re.compile(’(?P<head>b\w+)’)

result = regex.finditer(s)

for x in result:

print(type(x), x, x.group(), x.group(‘head’))

** **

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值