C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters

后端 未结 3 2085
[愿得一人]
[愿得一人] 2020-12-10 10:16

How is it possible to parse command-line arguments that are to be interpreted as paths? args[] contains strings that are automatically joined if they are quoted, e.g.:

3条回答
  •  [愿得一人]
    2020-12-10 11:03

    I had the same frustration. My solution was to use regular expressions. My expected input is a list of paths, some of which may be quoted. The above kludge doesn't work unless all the last arguments are quoted.

    // Capture quoted string or non-quoted strings followed by whitespace
    string exp = @"^(?:""([^""]*)""\s*|([^""\s]+)\s*)+";
    Match m = Regex.Match(Environment.CommandLine, exp);
    
    // Expect three Groups
    // group[0] = entire match
    // group[1] = matches from left capturing group
    // group[2] = matches from right capturing group
    if (m.Groups.Count < 3)
        throw new ArgumentException("A minimum of 2 arguments are required for this program");
    
    // Sort the captures by their original postion
    var captures = m.Groups[1].Captures.Cast().Concat(
                   m.Groups[2].Captures.Cast()).
                   OrderBy(x => x.Index).
                   ToArray();
    
    // captures[0] is the executable file
    if (captures.Length < 3)
        throw new ArgumentException("A minimum of 2 arguments are required for this program");
    

    Can anyone see a more efficient regex?

提交回复
热议问题