tags:

views:

42

answers:

3

I have this enum defitiion in file:

public enum IdentityState
{
    [EnumMember]
    New = 0,
    [EnumMember]
    Normal = 1,
    [EnumMember]
    Disabled = 2
}

{ some other data... }

And want to match only body of this enum (between {}), the match result i want is:

{
    [EnumMember]
    New = 0,
    [EnumMember]
    Normal = 1,
    [EnumMember]
    Disabled = 2
}

I make regex pattern like this:

public enum.*\w.*(?<enumBody>[\S|\s|]+\}{1})

but result is this:

{
    [EnumMember]
    New = 0,
    [EnumMember]
    Normal = 1,
    [EnumMember]
    Disabled = 2
}

{ some other data... }

Which is not what i expect because it also include next { some other data } string which i dont want. I dont know how make pattern to stop after first }.

A: 

try putting ^ at the front of your regex.

VOX
Thanks to all for help, finally i use this pattern:`public\s+enum\s+\w+\s*(?<enumBody>[^}]+})`
psulek
+1  A: 

Make the + quantifier lazy using ?. You don't need the {1} part.

public\s+enum\s+\w+\s*(?<enumBody>\{[\S|\s|]+?\})
Amarghosh
Isn't the first .* also needing to be made lazy? It strikes me that you are matching a curly bracket grouped at the end but the .* means you can have any amount of stuff between the enum and the {.
Chris
@Chris yeah, you're correct. Regex is not the right tool for code parsing (when used alone) to begin with.
Amarghosh
A: 

A lazy quantifier will work if that's the entire regular expression, but if you want to prevent the match from going past the end brace then it's better to explicitly disallow that character as part of the group by using [^}]:

public enum.*\w.*(?<enumBody>[^}]+})

If you don't want to include whitespace before the open brace, you can do the same thing on the front:

public enum[^{]*(?<enumBody>{[^}]+})
Quartermeister