正则如何递归匹配大括号?

我有一段字符串:

require './test.php';

function test() {
    if (true) {
        foreach ($arr as $v) {
        // ...
        }
    }
}

echo 333;
test();

function test2() {
    if (true) {
        foreach ($arr as $v) {
        // ...
        }
    } else {
        // ...
    }
}

即函数内有N多匹配的{}。

现在想正则匹配出以上字符串所有function,即函数{}包裹的字符串,如何操作?
麻烦PHP或Python示例,多谢。

阅读 10.5k
3 个回答

.net中有平衡组可以实现任意层嵌套的匹配, phppython中的正则没有支持动态表达式语言,因此无法实现任意层嵌套的匹配

我看题主的问题中虽然提到了递归,但其实只是说想要函数的大括号包裹的部分,好像并没有提到要把里面的if, foreach之类的语法也要分析出来,所以如果只是希望一个简单的实现的话,这样如何

<?php
$raw = <<<'EOT'
require './test.php';

function test() {
    if (true) {
        foreach ($arr as $v) {
        // ...
        }
    }
}

echo 333;
test();

function test2() {
    if (true) {
        foreach ($arr as $v) {
        // ...
        }
    } else {
        // ...
    }
}
EOT;
$matches = [];
preg_match_all('/function (\S+)\s?\{(.*?)\}/s', $raw, $matches);
print_r($matches);

运行结果

Array
(
    [0] => Array
        (
            [0] => function test() {
    if (true) {
        foreach ($arr as $v) {
        // ...
        }
            [1] => function test2() {
    if (true) {
        foreach ($arr as $v) {
        // ...
        }
        )

    [1] => Array
        (
            [0] => test()
            [1] => test2()
        )

    [2] => Array
        (
            [0] =>
    if (true) {
        foreach ($arr as $v) {
        // ...

            [1] =>
    if (true) {
        foreach ($arr as $v) {
        // ...

        )

)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进