-2

I have a string, that looks like a method:

"method(arg1,arg2,arg3);"

And I need to get all of the arguments in it as a string, I.e:

"arg1"
"arg2"
"arg3"

How can I do it? I have tried the following code:

var input = LineText;
var split = input.Split(',');
var result = String.Join(",", split.Skip(1).Take(split.Length - 2));
var split2 = input.Split(',');
var result2 = String.Join(",", split.Skip(2).Take(split.Length - 2));
var split3 = input.Split(',');
var result3 = String.Join(",", split.Skip(3).Take(split.Length - 2));

However it doesn't work correctly.

I need not a regex.

Byte
  • 55
  • 11
  • 1
    Try using Regular Expressions, at least use a regular expression to extract what are between brackets, then split them using the comma as a delimiter/separator. Or create your own "tokenizer" but this would be somewhat hard – user9335240 Oct 12 '18 at 12:58
  • nice idea,but can u provide a code?im not skilled in c# – Byte Oct 12 '18 at 12:59
  • 1
    @Byte that's not how StackOwerflow works, that's how freelancers work - you give a task and money, he provides you a code. – Renatas M. Oct 12 '18 at 13:01
  • @Reniuz I know,but im not giving a hard task.And i gived a question to him,is he can provide a code? – Byte Oct 12 '18 at 13:02
  • @Reniuz im not sure,a guy who writed a name of stackoverflow wrong,can know a how it works. – Byte Oct 12 '18 at 13:03
  • 1
    @Byte; You should at least show your own attempt. If you don't know how to write code in C# you are either using the wrong language or the wrong site. – Tim Schmelter Oct 12 '18 at 13:03
  • @TimSchmelter i tried,look at it – Byte Oct 12 '18 at 13:06
  • That's better. Now you could take a look at string.IndexOf, string. Substring methods. You can use the first one to find index of `(` and `)` symbols. Then extract the `arg1,arg2,arg3` and then use a split with `,` – Renatas M. Oct 12 '18 at 13:10
  • @Byte - `gived` -> `gave` | `writed` -> `wrote` - https://www.gingersoftware.com/content/grammar-rules/verbs/list-of-irregular-verbs/ – Rand Random Oct 12 '18 at 13:20
  • Possible duplicate of [How to get text between nested parentheses?](https://stackoverflow.com/questions/19693622/how-to-get-text-between-nested-parentheses) – John Alexiou Oct 12 '18 at 13:34
  • @ja72 its not duplicate.My question is not about regex. – Byte Oct 12 '18 at 14:46

3 Answers3

1

You can use regex or with this simple string pure string methods. First find the beginning and the end of the brackets with String.IndexOf. Then use Substring and Split:

static string[] ExtractArguments(string methodSig)
{
    int bracketStart = methodSig.IndexOf('(');
    if (bracketStart == -1) return null;
    int bracketEnd = methodSig.IndexOf(')', bracketStart + 1);
    if (bracketEnd == -1) return null;
    string arguments = methodSig.Substring(++bracketStart, bracketEnd - bracketStart);
    return arguments.Split(',').Select(s => s.Trim()).ToArray();
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • OP said `And I need to get all of the arguments in it as a string` - so maybe `string.Join(Environment.NewLine, ExtractArguments(methodSig));` is missing. – Rand Random Oct 12 '18 at 13:24
  • @RandRandom: i'm pretty sure OP needs all arguments as strings, so three strings in this sample. If he just needs the arguments as a single substring, that's in the variable `arguments` in the method above. – Tim Schmelter Oct 12 '18 at 13:36
0

An alternative solution using regex:

var s = "method(arg1,arg2,arg3);";
// Use regex to match the argument sequence "arg1,arg2,arg3"
var match = Regex.Match(s, @"^\w+\((.+)\);$");
// Split the arguments and put them into an array
string[] arguments = match.Groups[1].ToString().Split(',').ToArray();
alxnull
  • 909
  • 9
  • 18
  • Is returns a First argument? To return 2nd and 3rd i need to enter number in Groups[]? – Byte Oct 12 '18 at 13:28
  • @Byte No, `Groups[1]` will return all arguments between the brackets (`arg1,arg2,arg3`). `Split` will then seperate the arguments. So, the first argument would be `arguments[0]`, the second in `arguments[1]` etc. – alxnull Oct 12 '18 at 13:30
  • Thanks, Tim Is answered my question, but i will try your answer too, and Mark as answer too, if it works.. – Byte Oct 12 '18 at 13:36
0

Here is a regex expression that can handle nested parentheses

static class Program
{

    static readonly Regex regex = new Regex(@"
\(                    # Match (
(
    [^()]+            # all chars except ()
    | (?<Level>\()    # or if ( then Level += 1
    | (?<-Level>\))   # or if ) then Level -= 1
)+                    # Repeat (to go from inside to outside)
(?(Level)(?!))        # zero-width negative lookahead assertion
\)                    # Match )",
        RegexOptions.IgnorePatternWhitespace);

    /// <summary>
    /// Program Entry Point
    /// </summary>
    /// <param name="args">Command Line Arguments</param>
    static void Main(string[] args)
    {

        var input = "method(arg1,arg2,arg3(x));";

        var match = regex.Match(input);

        if(match != null)
        {

            string method = input.Substring(0, match.Index);                        // "method"
            string inside_parens = input.Substring(match.Index+1, match.Length-2);  // "arg1,arg2,arg3"   
            string remainer = input.Substring(match.Index+match.Length);            // ";"
            string[] arguments = inside_parens.Split(',');

            // recreate the input
            Debug.WriteLine($"{method}({string.Join(",", arguments)});");
            // Output: "method(arg1,arg2,arg3(x));"
        }

    }
}

Code was blatanlty stolen from this SO post.

John Alexiou
  • 28,472
  • 11
  • 77
  • 133