dongxun5349 2015-07-26 10:51
浏览 46
已采纳

too long

Is it possible to write a regex which would take input like 'sqrt(2 * (2+2)) + sin(pi/6)' and transform it into '\sqrt{2 \cdot (2+2)} + \sin(\pi/6)'?

The problem is the 'sqrt' and parentheses in it. It is obvious I can't simply use something like this:

/sqrt\((.?)\)/ -> \\sqrt{$1}

because this code would create something like this '\sqrt{2 \cdot (2+2)) + \sin(\pi/6}'.

  • 写回答

3条回答 默认 最新

  • dpy3846 2015-07-26 23:11
    关注

    My solution: it simply go throw the string converted to char array and tests if a current substring starts with $latex, if it does second for-cycle go from this point in different direction and by parentheses decides where the function starts and ends. (startsWith function)

    Code:

    public static function formatFunction($function, $latex, $input) {
        $input = preg_replace("/" . $function . "\(/", $latex . "{", $input);
        $arr = str_split($input);
    
        $inGap = false;
        $gap = 0;
    
        for ($i = count($arr) - 1; $i >= 0; $i--) {
            if (startsWith(substr($input, $i), $latex)) {
                for ($x = $i; $x < count($arr); $x++) {
                    if ($arr[$x] == "(" || $arr[$x] == "{") { $gap++; $inGap = true; } 
                    else if ($arr[$x] == ")" || $arr[$x] == "}") {  $gap--; }
    
                    if ($inGap && $gap == 0) {
                        $arr[$x] = "}";
                        $inGap = false;
                        break;
                    }
                }
            }
            $gap = 0;
        }
    
        return implode($arr);
    }
    

    Use:

    self::formatFunction("sqrt", "\\sqrt", 
    "sqrt(25 + sqrt(16 - sqrt(49)) + (7 + 1)) + sin(pi/2)");
    

    Output:

    \sqrt{25+\sqrt{16-\sqrt{49}}+(7+1)}+\sin (\pi/2)
    

    Note: sin and pi aren't formated by this code, it's only str_replace function...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程