TyperMan1133
TyperMan1133

Reputation: 65

How can i place a regex pattern inside another regex pattern without having mismatches

Here is my regex pattern (without spaces atm):

(method)\((.*?),(.*?)\)|(print)\((.*?)\)

And the result always returns:

"method(a,print(hello world)"

instead of:

"method(a,print(hello world))"

How can I capture everything while still keeping the outer brackets?

Upvotes: 0

Views: 99

Answers (1)

Kao
Kao

Reputation: 106

This uses a special construct called balancing groups to achieve recursiveness and capture more than one level of nesting in a method, should it be required. The commands captured are placed inside of the group "commands"

var regex = new Regex(@"method
[(]
(?<action>\w+)\s*,\s*
(\s*
    (?<commands>\w+
    (;|
        ((?<open>[(])[^(]*?)+
        (?<close-open>[)])+
        (?(open)(?!))
    ))+
\s*)+
[)]", RegexOptions.IgnoreWhitespace | RegexOptions.ExplicitCapture);

Here is a permalink to the regex. If you look in there, you will see the follwing table as a result:

enter image description here

As seen here, the regex has matched 4 commands in the 2nd line, under in which the action is a, in order to get those results, you can do regex.Match(foo).Groups["commands"].Captures.Select(c => c.Value)

Upvotes: 2

Related Questions