tags:

views:

73

answers:

4

I'm stuck with regular expressions. The program is a console application written in C#. There are a few commands. I want to check the arguments are right first. I thought it'll be easy with Regex but couldn't do that:

var strArgs = "";

foreach (var x in args)
{
    strArgs += x + " ";
}
if (!Regex.IsMatch(strArgs, @"(-\?|-help|-c|-continuous|-l|-log|-ip|)* .{1,}"))
{
    Console.WriteLine("Command arrangement is wrong. Use \"-?\" or \"-help\" to see help.");
    return;
}

Usage is:

program.exe [-options] [domains]

The problem is, program accepts all commands. Also I need to check "-" prefixed commands are before the domains. I think the problem is not difficult to solve.

Thanks...

+2  A: 

First, to parse command line arguments don't use regular expressions. Here is a related question that I think you should look at:

But for your specific problem with your regular expression - the options are optional and then you match against a space followed by anything at all, where anything can include for example invalid domains and/or invalid options. So far example this is valid according to your regular expression:

program.exe -c -invalid

One way to improve this by being more precise about the allowed characters in a domain rather than just matching anything.

Another problem with your regular expressions is that you don't allow spaces between the switches. To handle that you probably want something like this:

(?:(?:-\?|-help|-c|-continuous|-l|-log|-ip) +)*

I'd also like to point out that you should use string.Join instead of the loop you are currently using.

string strArgs = string.Join(" ", args);
Mark Byers
+4  A: 

Since you will end up writing a switch statement to process the options anyway, you would be better off doing the checking there:

switch(args[i])
{
case "-?": ...
case "-help": ...
...
default:
  if (args[i][0] == '-')
    throw new Exception("Unrecognised option: " + args[i]);
}
Marcelo Cantos
Thanks for your answer :)
Proton
+1  A: 

Don't reinvent the wheel, handling command line arguments is a solved problem.

I've gotten good use out of the Command Line Parser Library for .Net.

qstarin
I've never actually seen that library, but I like the idea. Thanks for sharing. Now I have a good library to goto for attributes examples too when I want to explain them to someone ;)
drachenstern
A: 

Actually the easiest way to achieve command line argument parsing is to create a powershell commandlet. That gives you a really nice way to work with arguments.

Bernd