[英]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.