你原来的表达就好了,我们只是在它周围添加一个捕获组,
([A-Za-z]+:)
测试
# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"([A-Za-z]+:)"
test_str = "testing:"
subst = "\"\\1\""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
输出
"testing:"
re.sub 示例
result = re.sub(pattern, repl, string, count=0, flags=0);
result = re.sub('abc', '', input) # Delete pattern abc
result = re.sub('abc', 'def', input) # Replace pattern abc -> def
result = re.sub(r'\s+', ' ', input) # Eliminate duplicate whitespaces
result = re.sub('abc(def)ghi', r'\1', input) # Replace a string with a part of itself
正则表达式电路
jex.im 可视化正则表达式: