相关疑难解决方法(0)

用于匹配函数和捕获其参数的正则表达式

我正在研究一个计算器,它需要字符串表达式并对它们进行评估.我有一个函数,使用Regex在表达式中搜索数学函数,检索参数,查找函数名称并对其进行求值.我遇到的问题是,如果我知道将会有多少参数,我只能做到这一点,我无法正确使用正则表达式.如果我只是通过字符拆分()字符的内容,,那么我不能在该参数中进行其他函数调用.

这是函数匹配模式: \b([a-z][a-z0-9_]*)\((..*)\)\b

它只适用于一个参数,我可以为每个参数创建一个组,不包括嵌套函数内的参数吗?例如,它将匹配:func1(2 * 7, func2(3, 5))并为:2 * 7和创建捕获组func2(3, 5)

这里我用来评估表达式的函数:

    /// <summary>
    /// Attempts to evaluate and store the result of the given mathematical expression.
    /// </summary>
    public static bool Evaluate(string expr, ref double result)
    {
        expr = expr.ToLower();

        try
        {
            // Matches for result identifiers, constants/variables objects, and functions.
            MatchCollection results = Calculator.PatternResult.Matches(expr);
            MatchCollection objs = Calculator.PatternObjId.Matches(expr);
            MatchCollection funcs = Calculator.PatternFunc.Matches(expr);

            // Parse the expression for …
Run Code Online (Sandbox Code Playgroud)

c# regex

17
推荐指数
3
解决办法
2万
查看次数

标签 统计

c# ×1

regex ×1