Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace curly braces and its contents in a string

Tags:

c#

regex

replace

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?

like image 974
Zannith Avatar asked Oct 04 '16 14:10

Zannith


3 Answers

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

like image 87
Gilad Green Avatar answered Nov 14 '22 21:11

Gilad Green


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;
        }
like image 21
WizxX20 Avatar answered Nov 14 '22 22:11

WizxX20


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:

  1. 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.

  2. 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.

like image 44
Baptiste Chardon Avatar answered Nov 14 '22 22:11

Baptiste Chardon