Alex
Alex

Reputation: 11

RegEx and an optional string

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

Upvotes: 0

Views: 460

Answers (2)

Alan Moore
Alan Moore

Reputation: 75222

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.

Upvotes: 1

Rubens Farias
Rubens Farias

Reputation: 57946

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

Upvotes: 0

Related Questions