How to match nested function calls (pairs of brackets) using a regular expression (recursive?)

I am looking for a regular expression (**) that will match an unknown number of nested functions. So

expression function(expression) function(function(expression)) function(function(function(expression))) etc. 

everything will fit. But, for example, if I add an extra closing bracket to the end, it will not be included in the match.

(**) Please do not answer that it would be easier to do this by playing (and counting the brackets) rather than using a regular expression - after I scratched my head a bit, I already know that!

+4
source share
3 answers

I am looking for a regular expression (**) that will match an unknown number of nested functions.

Some regex implementations support recursive matching (Perl, PHP, .NET), but JavaScript does not work. So, the answer to your question: no, this is not possible.

+5
source

This is not recursive, but it is a trick.

BACKGROUND:

  • Function names are alpha-numeric / underscores with a possible white space.
  • Function names do not start with a number.
  • There are no parentheses in the expressions.
  • There is only one expression inside functions.

CODE:

 var target = "function(function(function(expression)))"; var pattern = /\s*([a-zA-Z_]\w*[(](\s*[a-zA-Z_]\w*[(]|[^()]+[)]|[)])+[)])/; var matches = target.match(pattern); var target= matches[1]; 

REGULAR DISTRIBUTION OF EXPRESSIONS:

 \s* // 0+ white space characters ( // Capture group for what you want [a-zA-Z_] // 1 letter/underscore \w* // 0+ word characters (alpha-numeric/underscore) [(] // left parenthesis ( // PIECES: \s* // 0+ white space characters [a-zA-Z_] // 1 letter/underscore \w* // 0+ word characters (alpha-numeric/underscore) [(] // left parenthesis | // OR [^()]+ // 1+ non-parenthesis characters [)] // right parenthesis | // OR [)] // right parenthesis )+ // 1+ of these PIECES [)] // right parenthesis ) 
+5
source

It is worth noting that Bart Kirs replies that some regular expression mechanisms (with the exception of Javascript) have advanced functions to ensure recursive matching, but such a function should not be considered a regular expression in accordance with the formal definition.

0
source

Source: https://habr.com/ru/post/1436159/


All Articles