Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Capture results between delimiters. Content may contain a delimiter character

I have the following reg exp: /@\w+(\(((?:(?!\))\S|\s)*)\))?/m

And the value I’m expecting are template files like:

@for($i = 0; $i < 10; $i++)
    {{ $i }}
@endfor

@if(
    !empty($name)
    && $name == 'Carlos'
)
    Hi Carlos
@endif

@csfr

I’m having trouble capturing the full content from @if parenthesis.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The expected result would be:

!empty($name)
&& $name == 'Carlos'

But it returns this instead because of the closing parenthesis from the empty function:

!empty($name

How to capture the full expression, since this could contain calls to other functions?

Regexp debug link: https://regex101.com/r/58ZbXe/1

>Solution :

You can use

@\w+(\(((?:[^()]++|(\g<1>))*)\))?

See the regex demo.

Details:

  • @ – a @ char
  • \w+ – one or more word chars
  • (\(((?:[^()]++|(\g<1>))*)\))? – Group 1 (optional):
    • \( – a ( char
    • ((?:[^()]++|(\g<1>))*) – Group 2:
      • (?:[^()]++|(\g<1>))* – zero or more repetitions of either one or more chars other than ( and ) or Group 1 pattern
    • \) – a ) char.
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading