如何替换字符串中的花括号及其内容 [英] How to replace curly braces and its contents in a string
问题描述
我遇到了一个问题,试图用一个外部值替换用花括号划定的字符串的某些内容.
I have run into an issue of trying to replace certain contents of a string delineated with curly braces with an outside value.
相关代码示例:
string value = "6";
string sentence = "What is 3 x {contents}";
# insert some sort of method sentence.replace(value,"{contents}");
用值替换{contents}"的最佳方法是什么,因为花括号内的名称可能会改变,但无论名称如何,它都会包含在花括号内.
What is the best method for replacing "{contents}" with value, given that the name inside the curly braces may change but whatever the name, it will be contained within the curly braces.
我对正则表达式进行了一些研究,要么我迷失了概念,要么找不到相关的语法来完成我想要做的事情.这是实现这一目标的最佳方式吗?如果是,如何实现?如果不是,有什么更好的方法可以实现这一目标?
I looked a bit into regex and either the concepts were lost on me or I could not find relevant syntax to accomplish what I am trying to do. Is that the best way to accomplish this, and if so how? If not what would be a better method to accomplish this?
推荐答案
使用 Regex.Replace
:
string value = "6";
string sentence = "What is 3 x {contents}";
var result = Regex.Replace(sentence, "{.*?}", value); // What is 3 X 6
MSDN 是个好地方开始理解正则表达式
MSDN is a good place to start for understanding regex
这篇关于如何替换字符串中的花括号及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!