I want to find values ​​between {}

I am working with regular expressions (Regex) but can't find the exact output. I want to find values ​​between two curly braces

{ Value } = value

      

I am using the following pattern, but I am not getting the exact output; it does not remove the "{" first ...

string pattern = "\\{*\\}"; 

      

If my value {girish}

it returns{girish

Instead, I want girish

as output ...

+2


a source to share


3 answers


I'm surprised the pattern works by starting with it - it must match zero or more parentheses. You need to group your content in a parenthesis:

string pattern = @"\{([^}]*)\}";

      



Then, extract the contents of the mapped group. You didn't specify what code you are using to fetch the output, but in this case it will be in group 1. For example:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string pattern = @"\{([^}]*)\}";
        Regex regex = new Regex(pattern);
        string text = "{Key} = Value";
        Match match = regex.Match(text);
        string key = match.Groups[1].Value;
        Console.WriteLine(key);
    }    
}

      

+4


a source


(?<=\{)(.*?)(?=\})

      

Gives you what's in between.



Mandatory note:
Keep in mind that Regex won't help if the parentheses are nested - you need something with a stack.

+3


a source


Try using this pattern:

\{(.*)\}

      

A backslash may be required.

+1


a source







All Articles