3

I'm using ruby. I'm looking to match the outer "if" group of this:

{#if x > 10}
    <p>{x} is greater than 10</p>
    {#if 5 > x}
        <p>{x} is less than 5</p>
    {/if}
{/if}

What I have so far is this regex:

\{#if(.*)}(.|\n)*?\{\/if\}

But that just matches the first /if statement instead of the last one (see https://rubular.com/r/4l89GlANV9AVCQ). Any ideas?

(I tried this recursive regex matcher I saw on Stack Overflow: https://rubular.com/r/7a4PYTtxFQftob, but I'm struggling to make it work for the above)

1 Answer 1

2

It's basically the same as the regex for balanced parentheses that you linked to, but since the markers here are of multiple characters rather than single characters, you would need to use a negative lookahead pattern instead of simply a negated character class to ensure a matching character in the middle isn't part of the markers for the balanced construct:

{#if.*?}(?>(?!{(?:#if.*?|\/if)}).|\g<0>)*{\/if}

Demo: https://rubular.com/r/7BU2FStPEP34W4

Note that you should enable MULTILINE mode with the m option in order for . to match a newline character.

Sign up to request clarification or add additional context in comments.

1 Comment

This is perfect!! I'm studying more into negative lookaheads now. I was racking my head for hours on this and your solution solved it. Thank you so much bhlsing! :) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.