python - 当找到或未找到正则表达式模式时记录消息(详细 re.sub)

标签 python regex string

re.sub 替换文本时:

import re
s = 'This is a sample123 text'
s = re.sub(r'sample\d+', 'another', s)
print(s)

是否有内置方法可以使 re.sub 变得冗长?即打印:

  • “模式...已找到并成功替换”

  • 或“模式...未找到”

我正要推出自己的功能:

def mysub(r1, r2, s):
    if re.search(r1, s):  # note: don't use re.match: it matches from beginning only
        print('Pattern %s found' % r1)
        return re.sub(r1, r2, s)
    else:
        print('Pattern %s not found' % r1)
        return s

但我认为也许开箱即用是可能的。

最佳答案

我认为你的问题的直接答案是否定的。据我所知,re 包中没有“详细”日志记录方法。也就是说,re.subn()在这里相当有用,因为它返回所做的替换的计数,这样您就可以避免在调用 re.sub() 之前测试 re.search()

例如:

import re

regex = r'sample\d+'
sub = 'another'
text = 'This is sample123 text'
[new_text, count] = re.subn(regex, sub, text)

message = f'{regex} matched, {count} substitutions' if count else f'{regex} not found'

print(message)
print(new_text)
# OUTPUT
# sample\d+ matched, 1 substitutions
# This is another text

关于python - 当找到或未找到正则表达式模式时记录消息(详细 re.sub),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53875129/

相关文章:

regex - 解析多行变长日志文件

c# - 在 CMD 中运行脚本可以工作,但是在 C# python 脚本中使用 Process.Start() 运行时失败

将字符串样式从 Arduino 转换为 C 通用样式

c - 从文件读取仅获取第一个字符

python - Graphite 烯在上下文管理器中运行所有解析器

python - Python中的数组排序问题

python - 如何在Python中使用正则表达式分割/etc/network/interfaces

.net - 如何过滤文件上传控件?

python - Pycharm 在数据帧连接后不键入提示

c - C 中字符串中的数字相乘