Is there a Regex-like that is capable of parsing matching symbols?

前端 未结 3 1342
天涯浪人
天涯浪人 2021-01-23 10:08

This regular expression

/\\(.*\\)/

won\'t match the matching parenthesis but the last parenthesis in the string. Is there a regular expression

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-23 10:47

    Given a string containing nested matching parentheses, you can either match the innermost sets with this (non-recursive JavaScript) regex:

    var re = /\([^()]*\)/g;
    

    Or you can match the outermost sets with this (recursive PHP) regex:

    $re = '/\((?:[^()]++|(?R))*\)/';
    

    But you cannot easily match sets of matching parentheses that are in-between the innermost and outermost.

    Note also that the (naive and frequently encountered) expression: /\(.*?\)/ will always match incorrectly (neither the innermost nor outermost matched sets).

提交回复
热议问题