Skip to content
Advertisement

Retrieving the top-level element with Regex

I have the string bellow:

JavaScript

What i’m trying is to find the value inside the @if(.*?) and the content between the brackets of the top level “@if”.

This is the pattern i’ve tried:

JavaScript

This is matching:

JavaScript

How can i go from the outside into the string and match the top level “@if”?

Advertisement

Answer

Use singleline flag, and remove lazy from .*?:

JavaScript

And since TAB is included in s, and with the singleline flag n as well, you only need s to match the white space.

See it here at regex101.

Edit

Here’s an alternative using recursion, to manage multiple groups of braces.

JavaScript

Regex101 example.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement