views:

90

answers:

3

I'm working with regular expressions (Regex) but not finding the exact output. I want to find the values between two curly braces

{ Value } = value

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

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

If my value is {girish} it returns {girish

Instead of this I want girish as output...

+4  A: 

I'm surprised that pattern works to start with - it should be matching zero or more braces. You need to group the content within the brace:

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

Then extract the contents of the matched group. You haven't shown what code you're using to extract 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);
    }    
}
Jon Skeet
@Kobi: I don't think I was missing any braces, but I had the star in the wrong place :) (I was also escaping the brace when I didn't need to within the ^ section.)
Jon Skeet
hey jon, i have the following json string {"FirstName":"Json First"},{"UserID":9},{"Email":"Json First"}and i want to make regex for this..how can i skip the "," for the above expression....thnks
girish
Parsing JSON is not a task for which regular expressions are well-suited. There are many libraries that can parse JSON (JSON.NET, even the JavaScriptSerializer built into .NET 3.5) which would be more appropriate.
Dean Harding
+3  A: 
(?<=\{)(.*?)(?=\})

Will give you just what's in between.

Obligatory note:
Do keep in mind that Regex won't help if the braces are nested - you'd need something with a stack.

T.R.
Good point about nested bracing - although if braces were disallowed in the values, it would be feasible to match "closing brace, characters other than non-closing brace, end-of-line".
Jon Skeet
+1  A: 

Try it with this pattern:

\{(.*)\}

The backslashes may need to be escaped further.

Falle1234