How to check arguments with regex?

I am stuck with regular expressions. The program is a console application written in C #. There are several teams. First I want to check if the arguments are correct. I thought it would be easy with Regex, but could not do this:

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;
}

Using:

program.exe [-options] [domains]

The problem is that the program accepts all commands. I also need to check the "-" prefix commands in front of the domains. I think the problem is not difficult to solve.

Thank...

+3
source share
5 answers

Since you will eventually write a switch statement to handle the parameters anyway, you would be better off doing the check there:

switch(args[i])
{
case "-?": ...
case "-help": ...
...
default:
  if (args[i][0] == '-')
    throw new Exception("Unrecognised option: " + args[i]);
}
+4
source

-, . , , , :

- , , - , - , , / . :

program.exe -c -invalid

, , - .

, . , , , - :

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

, string.Join , .

string strArgs = string.Join(" ", args);
+2
+1

powershell. .

0

... , - ...

:

private string myVariable1;
private string myVariable2;
private Boolean debugEnabled = false;

:

loadArgs();

:

    private void loadArgs()
    {
        const string namedArgsPattern = "^(/|-)(?<name>\\w+)(?:\\:(?<value>.+)$|\\:$|$)";
        System.Text.RegularExpressions.Regex argRegEx = new System.Text.RegularExpressions.Regex(namedArgsPattern, System.Text.RegularExpressions.RegexOptions.Compiled);
        foreach (string arg in Environment.GetCommandLineArgs())
        {
            System.Text.RegularExpressions.Match namedArg = argRegEx.Match(arg);
            if (namedArg.Success)
            {
                switch (namedArg.Groups["name"].ToString().ToLower())
                {
                    case "myArg1":
                        myVariable1 = namedArg.Groups["value"].ToString();
                        break;
                    case "myArg2":
                        myVariable2 = namedArg.Groups["value"].ToString();
                        break;
                    case "debug":
                        debugEnabled = true;
                        break;
                    default:
                        break;
                }
            }
        }
    }

and to use it, you can use the command syntax with either a slash "/" or a dash "-":

myappname.exe /myArg1:Hello /myArg2:Chris -debug
0
source

Source: https://habr.com/ru/post/1764003/


All Articles