duanpoqiu0919 2013-12-11 11:00
浏览 58
已采纳

PCRE正则表达式函数解析器

I have a specific requirement to parse some basic pseudo code in (wait for it) PHP. The type of string that might need parsing is as follows:

MID(DATEDIFF(ymd,131001,131201),0,1)

Such that:

DATEDIFF(ymd,131001,131201) = 61
MID(60,0,1) = 6

The parsing of the individual expressions is not the problem, the problem is extracting the nested function calls with regex. I would really appreciate some input that might put me on the right track to be able to extract the function calls and their nested index - i.e.: Find the calls for MID (index = 0) and DATEDIFF (index = 1), which would allow me to evaluate the highest indexes first adn use those results in the lower indexes.

The best i can do with my feeble PCRE skills is the following:

$expression = 'MID(DATEDIFF(dmy,011213,021213),0,1)';
$regexp = '/^(DATEDIFF\(|MID\()(.*)\)/';
if (preg_match_all($regexp, $expression, $matches, PREG_OFFSET_CAPTURE)) {
    var_dump($matches); 
else echo "no match" . PHP_EOL;
  • 写回答

1条回答 默认 最新

  • dongshan1396 2013-12-11 15:41
    关注

    Have a look to this regex:

    (?P<function>\w+)(?=
        (?P<body>
           \(
              (?:
                [^()]
                |
                (?&body)
              )*
           \)
        )
    )
    

    Description

    Regular expression visualization

    Demo

    http://regex101.com/r/sY3eG0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码