I have run into an issue of trying to replace certain contents of a string delineated with curly braces with an outside value.
Relevant code example:
string value = "6";
string sentence = "What is 3 x {contents}";
# insert some sort of method sentence.replace(value,"{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?
Use Regex.Replace
:
string value = "6";
string sentence = "What is 3 x {contents}";
var result = Regex.Replace(sentence, "{.*?}", value); // What is 3 X 6
MSDN is a good place to start for understanding regex
I usually end up doing something like this:
public static string FormatNamed(this string format, params object[] args)
{
var matches = Regex.Matches(format, "{.*?}");
if (matches == null || matches.Count < 1)
{
return format;
}
if (matches.Count != args.Length)
{
throw new FormatException($"The given {nameof(format)} does not match the number of {nameof(args)}.");
}
for (int i = 0; i < matches.Count; i++)
{
format = format.Replace(
matches[i].Value,
args[i].ToString()
);
}
return format;
}
If I understand correctly what you want to do, and assuming you want to replace every instance of "{contents}" in your text, I see two solutions:
Using a simple string.Replace(string, string)
:
public static string InsertContent(string sentence, string placeholder, string value)
{
return sentence.Replace("{" + placeholder + "}", value);
}
Note that the function returns a new string object.
If you want to replace anything between brackets by a given value, or just have no control on what the string between brackets will be, you can also use a Regex
:
public static string InsertContent(string sentence, string value)
{
Regex rgx = new Regex(@"\{[^\}]*\}");
return rgx.Replace(sentence, value);
}
Again, the function returns a new string object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With