简体   繁体   中英

Parsing arguments in multi-line C-Functions

I have a few examples of the first line of implementation of C functions that I need to extract the parameters from. For example:

double FuncName1(char *testnum, char *hipin_source, char *hipin_sense,
                    char *lopin_source, char *lopin_sense, DMM_ResRange range, float delay) {

and

double FuncName2(char *testnum, char *hipin, char *lopin, DMM_ResRange range, float delay, bool offset) {

Is there any RegEx that I can use in C# to extract function name, return type, but more importantly the arguments?

EDIT: I am developing in C# and need to parse C-source code files creating objects like Func that has string Name, string ReturnType, List with Arg object having string argType, and string argName

EDIT 2: Well, I finally tried and it is not working... may be I did not define those right... I am trying to parse a function call that either coded like this:

     DCPS_Apply(1,    // Module (optional comment)
           5.0,  // Voltage (optional comment)
           2.0); // Current (optional comment)

or like this:

     DCPS_Apply(1, 5.0, 2.0); // optional comment

and I need function name and the arguments...

Try following:

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input =
                @"double FuncName1(char *testnum, char *hipin_source, char *hipin_sense,
                    char *lopin_source, char *lopin_sense, DMM_ResRange range, float delay) { }
                  double FuncName2(char *testnum, char *hipin, char *lopin, DMM_ResRange range, float delay, bool offset) { }
                ";

            string pattern1 = @"(?'type'\w+)\s+(?'name'[^(]+)\((?'parameters'[^)]+)\)";                    
            string pattern2 = @"(?'key'[^\s]+)\s+(?'value'[*\w]+),?";

            MatchCollection matches1 = Regex.Matches(input, pattern1);

            foreach (Match match1 in matches1.Cast<Match>())
            {
                string parameters = match1.Groups["parameters"].Value;
                MatchCollection matches2 = Regex.Matches(parameters, pattern2);
                string[] key_value = matches2.Cast<Match>().Select((x, i) => string.Format("Key[{0}] : '{1}', Value[{0}] : '{2}'", i, x.Groups["key"].Value, x.Groups["value"].Value)).ToArray();
                Console.WriteLine("Type : '{0}', Name : '{1}', Parameters : '{2}'", match1.Groups["type"].Value, match1.Groups["name"].Value, string.Join(";", key_value));
            }
            Console.ReadLine();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM