开发者

Invoke default command line parsing method from any application

I am passing in a complex string as an argument to my Console application. I noticed that the resultant string[] args array in my Main method is what I want that string to be parsed as.

Now, I want to be able to parse strings of this format and the get the same string[] in other parts of my framework, outside of my console application/process as well and do not want to reinvent the wheel. I tried to see if I could find and invoke the framework method that is used to parse command line arguments that are passed to the Main method but could no开发者_Python百科t find anything. I read about some command line parsing options including NDesk but cannot use that in my present situation.

Anyone aware of this framework method(s)? Or any other ideas to go about this?


Use a Regular Expression:

string input = "this is \"a string\" separated by spaces \"with quotes\" also";
Regex r = new Regex("[^\\s\"']+|\"([^\"]*)\"|'([^']*)'");
var matches = r.Matches(input);

Figure an explanation would be good:

[^\\s\"']+ matches 1+ characters up to a space or a double quote

| OR

\"([^\"]*)\" matches 0+ characters inside of double quotes that is not a double quote itself

| OR

'([^']*)' matches 0+ characters inside of a single quote that is not a single quote itself

Also, I'm not great with .net Regex, but from what I can tell, they're weird when it comes to matching groups. For me to get the string without the quotes around them, I had to do this weird loop:

 var matches = r.Matches(input);
 foreach (Match match in matches)
 {
      Console.WriteLine(match.Groups[1].Value);
 }

There was an API call you could make if your are running on windows (it is supported past vista, regardless of what the pinvoke.net says). Obviously this is not cross-platform.

[DllImport("shell32.dll", SetLastError = true)]
static extern IntPtr CommandLineToArgvW(
   [MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
   out int pNumArgs);

Example code here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜