用 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/