'regex get anything between double curly braces

I need to get the text between double curly braces in .NET. I got this:

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

However, it also includes the double curly braces. Is there a way to exclude them?



Solution 1:[1]

Groups[0] is whole substring

Groups[1] and so on returns text between ()

Try

new Regex(@"\{{([^}]+)\}}").Match("dfdf{{456gfd}}3453").Groups[1]

Solution 2:[2]

(This answer is not specific to .NET)

For a basic capturing regexp that is non-greedy (and so will match the smallest string sourrounded by double quotes) and including text enclosed in single curly braces in the match:

{{(([^}][^}]?|[^}]}?)*)}}

Example

Given

{{first group}} nothing {{second {special} group}}

We will come away with the following captures

  • first Group
  • second {special} group

Explanation

  • {{ :: Matches the opening double braces
  • (...) :: Our desired position capture
    • (...|...)* :: Matches repeated occurrences of either of the two alternatives separated by the |
      • [^}][^}]? :: Matches anything that is not the closing double braces, }} (the ? is necessary to ensure we can match odd and even length strings)
      • [^}]}? :: Matches an optional single closing brace that is no preceded directly with a prior brace.
  • }} :: Matches the closing double braces

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rambalac
Solution 2 Shon