当前位置:主页 > 技术文档 > Python 下载

【Python标准库之字符串处理库、文件及目录操作、时间日期】知识点结构图

  • 更新:2021-01-23 17:54:19
  • 大小:1.69 MB
  • 热度:695
  • 审核:冉风华
  • 类别:技术文章
  • 格式:PDF

  • 资源介绍
  • 相关推荐

用模式修改字符串

除了搜索文本之外,re还支持使用正则表达式作为搜索机制来修改文本,而且替换(repla-cement)可以引用模式中的匹配组作为替代文本的一部分。使用sub()可以将一个模式的所有出现替换为另一个字符串。

新建re_sub.py文件。

import re

bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold**. This **too**.'
print('Text:', text)
print('Bold:', bold.sub(r'<b>\1</b>', text))

以上代码输出结果为:

Text: Make this **bold**. This **too**.
Bold: Make this <b>bold</b>. This <b>too</b>.

以上代码可以引用\num语法插入与模式匹配的文本的引用。

要在替换中使用命名组,可以使用语法\g<name>。

新建re_sub_named_groups文件。

import re

bold = re.compile(r'\*{2}(?P<bold_text>.*?)\*{2}')
text = 'Make this **bold** .This **too**.'
print('Text:', text)
print('Bold:', bold.sub(r'<b>\g<bold_text></b>', text))

以上代码输出结果为:

Text: Make this **bold** .This **too**.
Bold: Make this <b>bold</b> .This <b>too</b>.

以上代码,\g<name>语法还适用于编号引用,使用这个语法可以消除组编号和外围字面量数字之间的模糊性。

向count传入一个值可以限制完成的替换数。

新建re_sub_count文件。

import re

bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold** .This **too**.'
print('Text:', text)
print('Bold:', bold.sub(r'<b>\1</b>', text, count=1))

以上代码输出结果为:

Text: Make this **bold** .This **too**.
Bold: Make this <b>bold</b> .This **too**.

以上代码由于count为1,所以只完成了第一个替换。

subn()的工作月sub()很相似,只是它同时返回修改后的字符串和完成的替换数。

新建re_subn文件。

import re

bold = re.compile(r'\*{2}(.*?)\*{2}')
text = 'Make this **bold** .This **too**.'
print('Text:', text)
print('Bold:', bold.subn(r'<b>\1</b>', text))

以上代码输出结果为:

Text: Make this **bold** .This **too**.
Bold: ('Make this <b>bold</b> .This <b>too</b>.', 2)

以上代码中搜索模式有两次匹配。

资源下载

资源下载地址1:https://pan.baidu.com/s/1E1jyB4u9aIbPxYJzWt401g

相关资源

网友留言