Python 使用正则表达式将捕获的单词替换为捕获的单词和引用

Python 使用正则表达式将捕获的单词替换为捕获的单词和引用,python,regex,Python,Regex,我有一个字符串:“testing:”,并希望将其替换为“testing:”。 换句话说,在字符串中的单词周围添加引号 我试过使用 re.sub('[a-zA-Z]+:', '"${name}"',word) 但这只是将其替换为{name}您的原始表达式很好,我们只需在其周围添加一个捕获组 ([A-Za-z]+:) 试验 输出 re.sub的示例 正则表达式电路 可视化正则表达式: 您可以使用以下选项来指代整个比赛: backreference\g替换由RE匹配的整个子字符串 代码: wor

我有一个字符串:
“testing:”
,并希望将其替换为
“testing:”
。 换句话说,在字符串中的单词周围添加引号

我试过使用

re.sub('[a-zA-Z]+:', '"${name}"',word)

但这只是将其替换为
{name}

您的原始表达式很好,我们只需在其周围添加一个捕获组

([A-Za-z]+:)
试验 输出 re.sub的示例
正则表达式电路 可视化正则表达式:

您可以使用以下选项来指代整个比赛:

backreference
\g
替换由RE匹配的整个子字符串

代码:

word=re.sub(r'[a-zA-Z]+:',r''\g'',word)

重新导入
word='测试:'
word=re.sub(r'[a-zA-Z]+:',r''\g'',word)
打印(word)#=>“测试:”

它捕获了表达式,但我在替换正则表达式StringEx时遇到了困难。谢谢!你能解释一下你在做什么吗substr@user3688791不要用捕获组包装整个模式,这会给正则表达式引擎增加一点开销。使用整个匹配的专用反向引用。您需要
re.sub(r'[a-zA-Z]+:',r''\g',word)
。无需捕获任何内容尝试:
re.sub('([a-zA-Z]+:)',r''1',word)
您需要
re.sub('[a-zA-Z]+:',r''g',word)
请参见
# 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:"
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
word = re.sub(r'[a-zA-Z]+:', r'"\g<0>"', word)
import re
word = 'testing:  '
word = re.sub(r'[a-zA-Z]+:', r'"\g<0>"',word)
print(word) # => "testing:"