How to match nested function invocations (bracket pairs) using a regular [removed]recursive?)

后端 未结 3 1924
甜味超标
甜味超标 2021-01-19 08:24

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

expression
function(expression)
function(function(expres         


        
相关标签:
3条回答
  • 2021-01-19 08:35

    Worth noting as per Bart Kiers's answer that some regex engines (excluding Javascript) have extended features to provide recursive matching - but such a feature shouldn't be considered to be a regular expression as per the formal definition.

    0 讨论(0)
  • 2021-01-19 08:46

    I'm 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. So, the answer to your question is: no, that is not possible.

    0 讨论(0)
  • 2021-01-19 08:47

    This isn't recursive, but it does the trick.

    PRECONDITIONS:

    • Function names are alpha-numeric/underscore with possible leading white space.
    • Function names do not start with a number.
    • Expressions have no parentheses in them.
    • There is only one expression nested within the 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 EXPRESSION DISSECTION:

    \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
    )
    
    0 讨论(0)
提交回复
热议问题