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.
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.