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

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?