【问题标题】:Replace captured word with captured word and quotations using regex [duplicate]使用正则表达式将捕获的单词替换为捕获的单词和引用[重复]
【发布时间】:2019-11-02 14:09:47
【问题描述】:

我有一个字符串:'testing: ' 并想用' "testing:" ' 替换它。 换句话说,在字符串内的单词周围添加引号

我尝试过使用

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

但这只是用{name}替换它

【问题讨论】:

  • 你想要re.sub(r'[a-zA-Z]+:', r'"\g<0>"',word)。无需捕捉任何东西
  • 试试:re.sub('([a-zA-Z]+:)', r'"\1"',word)
  • 你需要re.sub('[a-zA-Z]+:', r'"\g<0>"', word)stackoverflow.com/questions/7191209/…

标签: python regex


【解决方案1】:

你原来的表达就好了,我们只是在它周围添加一个捕获组,

([A-Za-z]+:)

Demo

测试

# 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

Reference

正则表达式电路

jex.im 可视化正则表达式:

【讨论】:

  • 它捕获了表达式,但我在替换正则表达式字符串时遇到了困难
  • 谢谢你!你能解释一下你在用 substr 做什么吗
  • @user3688791 不要使用捕获组来包装整个模式,这会增加正则表达式引擎的微小但开销。使用对整个匹配的专用反向引用。
【解决方案2】:

您可以使用\g<0> backreference 来指代整个比赛:

后向引用 \g<0> 替换了 RE 匹配的整个子字符串。

代码:

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

Python demo

import re
word = 'testing:  '
word = re.sub(r'[a-zA-Z]+:', r'"\g<0>"',word)
print(word) # => "testing:"  

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 2015-02-03
    相关资源
    最近更新 更多