Reputation: 69
I have got a problem with getting three params from console. For example the user enter to the console so line: '/s:http://asdasd.asd /e:device /f:create'
string params = Console.ReadLine(); // /s:http://asdasd.asd /e:device /f:create'
I need to get those params
string server = ""; //should be "http://asdasd.asd"
string entity = ""; //should be "device"
string function = "" //should be "create"
I can not understand how to do it. Help me please)
example console http://d.pr/i/kTpX
Upvotes: 1
Views: 139
Reputation: 11233
An even more simpler solution would be:
(?<=\:)[^ ]+
This single regex will return three groups.
Upvotes: 0
Reputation: 98750
You need 3 different regex (At least I can't find the common one) for this process. Because http://
destroy every regular expression on this case :)
string s = @"/s:http://asdasd.asd /e:device /f:create";
string reg1 = @"(?=/s:)[^ ]+";
string reg2 = "(?=/e:)[^ ]+";
string reg3 = "(?=/f:)[^ ]+";
Match match1 = Regex.Match(s, reg1, RegexOptions.IgnoreCase);
if (match1.Success)
{
string key1 = match1.Groups[0].Value.Substring(3);
Console.WriteLine(key1);
}
Match match2 = Regex.Match(s, reg2, RegexOptions.IgnoreCase);
if (match2.Success)
{
string key2 = match2.Groups[0].Value.Substring(3);
Console.WriteLine(key2);
}
Match match3 = Regex.Match(s, reg3, RegexOptions.IgnoreCase);
if (match3.Success)
{
string key3 = match3.Groups[0].Value.Substring(3);
Console.WriteLine(key3);
}
Output will be;
http://asdasd.asd
device
create
Here is a DEMO
.
Upvotes: 0
Reputation: 1139
Here's a regex example that does that and groups by what you need:
/s:([^ ]{1,100}) /e:([^ ]{1,100}) /f:([^ ]{1,100})
Also, I'd recommend using http://regexpal.com/ to learn how to create those.
Edit: This is a pretty specific example, not covering all possible cases. Test it in the website above for different inputs to make needed changes.
Upvotes: 0
Reputation: 9290
Split by space character, followed by a split at the first ':'. Something like:
string input = "/s:http://asdasd.asd /e:device /f:create";
string[] parameters = input.Split(' ');
foreach (string param in parameters)
{
string command = "";
string value = "";
command = param.Substring(0, param.IndexOf(':'));
value = param.Substring(param.IndexOf(':') + 1);
}
// Results:
// command: /s value: http://asdasd.asd
// command: /e value: device
// command: /f value: create
There might be libaries that can help you, or you could opt for regular expressions. But it isn't mandatory in this situation. Obviously there should be some error handling code in case of bad input, but I think you can manage that by yourself.
Upvotes: 1
Reputation: 19830
There are nice external utils for parsing input arguments. Insead of wrinting your own code you can use them. I known following:
It will be much easier for you.
Upvotes: 1