简体   繁体   English

使用命令行解析器解析字符串

[英]Parsing a string using command Line parser

I downloaded this package https://github.com/commandlineparser/commandline and I wanted to perform parsing for strings like我下载了这个 package https://github.com/commandlineparser/commandline我想对字符串进行解析

string str = "file:xxxx\\xxxx\\xxxxx.sh val:-a nsdd m";

so所以

file = xxxx\\xxxx\\xxxxx.sh
val = -a nsdd m

I wanted to know if anyone had a library in mind or has used the specified library to obtain the parameters specified in the string.我想知道是否有人想到了库或使用了指定的库来获取字符串中指定的参数。 I am having a hard time understanding the example on how to parse that string and obtain the file parameter and val parameter.我很难理解有关如何解析该字符串并获取文件参数和 val 参数的示例。 I know i could do string manipulation but I rather use an existing tested durable solution for this.我知道我可以进行字符串操作,但我宁愿为此使用现有的经过测试的持久解决方案。

I've used this library and it's a solid choice.我使用过这个库,这是一个不错的选择。

Here's a very basic sample using some of what you posted, see code comments for clarification.这是一个非常基本的示例,使用了您发布的一些内容,请参阅代码注释以进行说明。

class Program
{
    static void Main(string[] args)
    {
        // args a space separated array so you should use an array for your test
        // args are identified with the `-` so you should set args like `-f somefilenamehere`
        // args specified are -f and -v
        string[] arguments = new[] {"-f file:xxxx\\xxxx\\xxxxx.sh", "-v nsdd" };
        string file = string.Empty;
        string value = string.Empty;

        // you would pull your args off the options, if they are successfully parsed
        // and map them to your applications properties/settings
        Parser.Default.ParseArguments<Options>(arguments)
            .WithParsed<Options>(o =>
            {
                file = o.InputFile; // map InputFile arg to file property
                value = o.Value; // map Value arg to value property
            });


        Console.WriteLine($"file = {file}");
        Console.WriteLine($"value = {value}");
        Console.ReadLine();

        // output:
        // file =  file:xxxx\xxxx\xxxxx.sh
        // value =  nsdd

    }        
}

// the options class is used to define your arg tokens and map them to the Options property
class Options
{
    [Option('f', "file", Required = true, HelpText = "Input files to be processed.")]
    public string InputFile { get; set; }

    [Option('v', "value", Required = true, HelpText = "Value to be used")]
    public string Value { get; set; }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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