Rasmus Søborg
Rasmus Søborg

Reputation: 3695

Regex match all inside brackets inside brackets?

I want to find the following value

PROCEDURE test {
        test { }
}

from:

test {
    PROCEDURE test {
        test { }
    }
}

My current Regex is:

PROCEDURE.*?{.*?(\}){2}

But it does not match. Does anyone have any idea how I can accomplish this?

Upvotes: 0

Views: 275

Answers (2)

Casperah
Casperah

Reputation: 4554

What about this regex:

PROCEDURE\s+\w+\s*\{(?:.*?\{.*?\})*.*?\}

It matches pairs of {}.

However, if the procedure contains strings or comments that contain curly brackets it will fail.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213243

You would need to match pairs of { and } between the first { and the last }.

You can try out this regex: -

PROCEDURE[^{]*[{](?:[^{]*[{][^}]*[}])*[^}]*[}]

I have enclosed curly braces inside character class, so that you don't need to escape them, also with [^{]*, you won't need reluctant matching, as it will automatically stop at the first {.

Upvotes: 1

Related Questions