Search code examples
c#regextext-manipulation

Replace text place holders with Regular Expression


I have a text template that has text variables wrapped with {{ and }}.

I need a regular expression to gives me all the matches that "Include {{ and }}".

For example if I have {{FirstName}} in my text I want to get {{FirstName}} back as a match to be able to replace it with the actual variable.

I already found a regular expression that probably gives me what is INSIDE { and } but I don't know how can I modify it to return what I want.

/\{([^)]+)\}/

Solution

  • This pattern should do the trick:

    string str = "{{FirstName}} {{LastName}}";
    
    Regex rgx = new Regex("{{.*?}}");
    
    foreach (var match in rgx.Matches(str))
    {
        // {{FirstName}}
        // {{LastName}}
    }