views:

84

answers:

2

Hello,

I am having problems with an optional group in a regex (.NET syntax, and I'm using RegexOptions.Singleline).

"function (\w*).*?{(?:.*?\((.*?)\))?.*?}"

Also tried, to no avail: "function (\w*)[^{]+{(?:.*?\((.*?)\))?.*?}"

It looks like the group is not optional, because if I just add two parenthesis in FunctionWithNoParameters then all is working fine. The goal is to have two groups: the function name and their optional parameters. Can someone help me?

The text I'm trying to parse is something like:

 function test1
{
    param ([int]$parm2, [bool]$parm3)
}

function FunctionWithNoParameters { 

return "nothing"
}

function test2    {
  param([string]$parm1, 
        [int]$parm2, 
        [bool]$parm3)}

Thanks, Alex

A: 

Try this:

function (?<name>\w+)\s*?\{\s*?(?<param>param\s*\([\s\S]*?\))?[\s\S]*?\}

EDIT: Strange, I couldn't match that optional param group in my tests

Rubens Farias
A combination of the two could do the trick I think:`function (\w*)[^{]+{\s*(?<param>param\s*\([\s\S]*?\))?.*?}`but...now I get the word "param" and the parenthesis as well.
Alex
+1  A: 

This regex works for me given the sample data you provided:

@"function\s+(\w+)\s*\{\s*(?:param\s*\(([^()]*)\))?"

The main problem with your regex is this part: .*?\(. When you match the second function, the .*? scans all the way through that function and finds the opening parenthesis in the third function.

Alan Moore