You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用正则表达式将旧专有格式IF语句转换为C#兼容语法

解决方案

方案1:多轮循环替换(通用正则工具可实现,无需编码)

如果你用正则工具手动处理,可按以下步骤操作,适配所有嵌套场景:

  1. 替换IF语句(循环执行直到无匹配)
    匹配规则:
    IF\((?<cond>(?:[^(),]+|\((?:[^()]+|\([^()]*\))*\))+),(?<true>(?:[^(),]+|\((?:[^()]+|\([^()]*\))*\))+),(?<false>(?:[^(),]+|\((?:[^()]+|\([^()]*\))*\))+)\)
    
    替换模板:
    if (${cond}) { ${true} } else { ${false} }
    
    每次执行会替换最内层的IF语句,嵌套IF只需多执行几次替换即可完全转换。
  2. 替换等于判断符
    匹配规则:
    (?<![<>!=])=(?!=)
    
    替换为:
    ==
    
  3. 替换ROUND函数
    匹配规则:
    \bROUND\(
    
    替换为:
    Math.Round(
    

方案2:C# 代码实现(一次性完成转换)

如果是用C#直接开发转换工具,可直接用以下代码,利用.NET正则的平衡组能力自动处理嵌套:

using System;
using System.Text.RegularExpressions;

public class RecipeConverter
{
    private static readonly Regex IfRegex = new Regex(@"IF\((?<Cond>(?:[^(),]|(?<Open>\()|(?<-Open>\)))*(?(Open)(?!))),(?<TrueVal>(?:[^(),]|(?<Open>\()|(?<-Open>\)))*(?(Open)(?!))),(?<FalseVal>(?:[^(),]|(?<Open>\()|(?<-Open>\)))*(?(Open)(?!)))\)", RegexOptions.Compiled);
    private static readonly Regex RoundRegex = new Regex(@"\bROUND\(", RegexOptions.Compiled);
    private static readonly Regex EqualRegex = new Regex(@"(?<![<>!=])=(?!=)", RegexOptions.Compiled);

    public static string Convert(string input)
    {
        string result = IfRegex.Replace(input, match =>
        {
            string cond = EqualRegex.Replace(match.Groups["Cond"].Value.Trim(), " == ");
            string trueVal = Convert(match.Groups["TrueVal"].Value.Trim());
            string falseVal = Convert(match.Groups["FalseVal"].Value.Trim());
            return $"if ({cond}) {{ {trueVal} }} else {{ {falseVal} }}";
        });
        result = RoundRegex.Replace(result, "Math.Round(");
        return result;
    }
}

执行测试用例输出完全匹配要求的格式。

内容的提问来源于stack exchange,提问作者DeadZone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 22:57:02