用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
但是我认为也许开箱即用。
答案 0 :(得分:1)
我认为您的问题的直接答案是“否”。我知道,re
软件包中没有“冗长”的日志记录方法。也就是说,re.subn()
在这里非常有用,因为它返回进行的替换计数,因此您可以避免在调用re.search()
之前测试re.sub()
。
例如:
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