简体   繁体   English

如何在字符串中搜索文本并替换为其值

[英]how to search for a text in a string and replace with its value

I need to search for image_bid in string s and if exists need to replace that string with its value DEBUG in this case,I tried the following but doesn't seem to work,can anyone suggest how can I do that? 我需要在字符串s搜索image_bid,如果存在需要用它的值DEBUG替换该字符串,在这种情况下,我尝试了以下但似乎不起作用,任何人都可以建议我该怎么做?

import re
s = "cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/"

match = re.search('image_bid:(\w+)',s)
print match.group(1)

if match:
    final_value = s.replace('image_bid:(\w+)',match.group(1))
print final_value

MY OUTPUT:-
cols/sel/Pkg/Bin/LA/${image_bid:DEBUG}/

Expected output:-
cols/sel/Pkg/Bin/LA/DEBUG

The method replace() returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to max. 方法replace()返回字符串的副本,其中old的出现已被new替换,可选地将替换次数限制为max。

It doesn't seem like the replace method for string support regular expression, use re.sub instead: 它似乎不是字符串支持正则表达式的replace方法,而是使用re.sub

if match:
    final_value = re.sub(r'\${image_bid:\w+}',match.group(1), s)
print final_value
# cols/sel/Pkg/Bin/LA/DEBUG/

你可能想要这样的东西

final_value = re.sub(r'\$\{image_bid\:(\w+)\}/', r'\1', s)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 搜索和替换文本文件中的字符串 - Search and Replace a string in text file 如何在python中搜索和替换文本文件的多个值? - how to search and replace for multiple value of text file in python? 如何在字符串中搜索字典键并将其替换为值 - how do I search a string for dictionary key and replace it with value 如何用该字符串的递增值替换文本文件上的字符串 - How to replace a string on a text file with an incrementing value of that string 如何搜索和替换文件中的文本? - How to search and replace text in a file? Python - 如何替换文本文件中值未知的字符串? - Python - How to replace a string in a text file where value is not known? 搜索在其文本或其任何后代中包含字符串的元素 - Search for elements which contains a string in its text or in any of its descendant 如何在 Python 的嵌套字典中用其对应的 Boolean 值替换字符串值? - How can I replace a string value with its corresponding Boolean value in a nested dictionary in Python? 如何用新的字符串替换数组中的特定索引,然后将其恢复为原始值? - How to replace a specific index inside of an array with a new string, and then revert it back to its original value? 如何搜索并用封闭的字符替换文本文件? - How to search and replace with enclosed characters a text file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM