正则表达式解析函数和参数

时间:2014-01-06 23:30:01

标签: c# regex asp.net-mvc

我有以下字符串:

function(param1, param2, param3, param4, ..., paramN)

我需要一个正则表达式代码来将其解析为字符串数组:

function
param1
param2
param3
param4
.
.
.
paramN

我在网上尝试了几个例子,但似乎没有一个适合我。

[编辑]

没有提出建议。检查以上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;

namespace TestRegex
{
    class Program
    {
        static void Main(string[] args)
        {
            string Expression = String.Empty;

            while (Expression.Trim() != "EXIT")
            {
                Expression = Console.ReadLine();

                ///
                /// Get function name
                /// 
                var funcTags = Regex.Matches(Expression, @"b[^()]+\((.*)\)$");

                Console.WriteLine("Matches: " + funcTags.Count);
                foreach (var item in funcTags)
                    Console.WriteLine("FuncTag: " + item);

                ///
                /// Get parameters
                /// 
                var paramTags = Regex.Matches(Expression, @"\b[^()]+\((.*)\)$");

                Console.WriteLine("Matches: " + paramTags.Count);
                foreach (var item in paramTags)
                    Console.WriteLine("ParamTag: " + item);
            }
        }
    }
}

输出:

function("a", "b", "c");
Matches: 0
Matches: 0

这里出了点问题......感谢帮助。

1 个答案:

答案 0 :(得分:7)

根据你的功能有多复杂,这实际上可能非常棘手。通过 here 查看我的类似答案。要点是将正则表达式分解为两个问题。首先获取函数名称,然后获取参数。

总之,这将提取函数名称:

\b[^()]+\((.*)\)$

对于参数,它处理参数以及参数中的函数:

([^,]+\(.+?\))|([^,]+)

这将处理嵌套函数:

(?:[^,()]+((?:\((?>[^()]+|\((?<open>)|\)(?<-open>))*(?(open)(?!))\)))*)+

但是,如果你需要支持完整的C#语法,这很快就会变得棘手,例如:参数中的注释等。请参阅here进行讨论。

根据评论进行更新

道歉,我错过了一些错误(现已更正)。你错过了函数正则表达式中的第一个\。您也使用相同的模式来提取参数,而您需要如上所述的第二个正则表达式。此外,由于每行只有一个功能,您可以进行单一匹配。这段代码可以使用:

    static void Main( string[] args )
    {
        string Expression = "function(param1, param2)";            
        ///
        /// Get function name
        /// 
        var func = Regex.Match( Expression, @"\b[^()]+\((.*)\)$" );

        Console.WriteLine( "FuncTag: " + func.Value );
        string innerArgs = func.Groups[1].Value;
        ///
        /// Get parameters
        /// 
        var paramTags = Regex.Matches( innerArgs, @"([^,]+\(.+?\))|([^,]+)" );

        Console.WriteLine( "Matches: " + paramTags.Count );
        foreach( var item in paramTags )
            Console.WriteLine( "ParamTag: " + item );

    }

输出:

FuncTag: function(param1, param2)
Matches: 2
ParamTag: param1
ParamTag:  param2