在找到或没有正则表达式模式时记录消息(verbose re.sub)

2024-09-25 16:34:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但我想也许这是有可能的


Tags: sampletext文本importrereturnis模式
1条回答
网友
1楼 · 发布于 2024-09-25 16:34:39

我认为你的问题的直接答案是否定的。我知道在re包中没有“详细”的日志记录方法。也就是说,^{}在这里相当有用,因为它返回所做替换的计数,这样您就可以避免在调用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

相关问题 更多 >