Regular expression matching unescaped paired brackets and nested function calls

StackOverflow https://stackoverflow.com/questions/18339862

  •  25-06-2022
  •  | 
  •  

سؤال

Here's the problem: given a string like

"<p>The price for vehicles {capitalize(pluralize(vehicle))} is {format_number(value, language)}</p><span>{employee_name}</span><span>\{do not parse me}</span>"

I need (1) a regex pattern in PHP that matches all values between un-escaped pairs of curly brackets and (2) another regex pattern that matches function calls and nested function calls (once the first pattern is matched). Of course, if I could use one regex only for both tasks that would be awesome.

By the way, I can't use Smarty, Twig or any other library - that's the only reason I have to build a parsing mechanism myself.

Thanks a ton!

Solution (1) A partial solution for the first problem can be found here. Basically, we use the regex

(?={((?:[^{}]++|{(?1)})++)})
and find the matches at index 1 of the resulting array.

It's partial because I still need to find a way of ignoring escaped braces, though.

(2) I'm considering the use of recursive regex, as suggested by Mario. Will post result here.

Thanks, guys!

هل كانت مفيدة؟

المحلول

Copying the answer from the comments in order to remove this question from the "Unanswered" filter:

This appears to be what you're looking for:

(?<!\\){([^(){}]+)\(((?:[^(){}]+|\(((?2))\))*)\)}

Link: http://www.regex101.com/r/uI4qN0

~ answer per Jerry

Note: For comparison - simply ignoring escaped braces is accomplished by adding a negative lookahead (?<!\\) to the beginning of the expression, like so:

(?<!\\)(?={((?:[^{}]++|{(?1)})++)})
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top