2013-05-14 78 views
1

我从控制台获取三个参数时遇到问题。 例如,用户输入到控制台,这样行: '/ S:http://asdasd.asd/E:设备/ F:打造'String substring或reg expr

string params = Console.ReadLine(); // /s:http://asdasd.asd /e:device /f:create' 

我需要得到这些PARAMS

string server = ""; //should be "http://asdasd.asd" 
string entity = ""; //should be "device" 
string function = "" //should be "create" 

我无法理解怎么做。请帮助我)

例如控制台 http://d.pr/i/kTpX

+1

我会为正则表达式投票 – Saravanan 2013-05-14 08:21:30

回答

1

使用本:

`(?<=/s:)[^ ]+` 
`(?<=/e:)[^ ]+` 
`(?<=/f:)[^ ]+` 
1

分割由空格字符,随后在所述第一分割“:”。喜欢的东西:

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 

有可能是libaries,可以帮助你,或者你可以选择正则表达式。但在这种情况下它不是强制性的。显然,如果输入错误,应该有一些错误处理代码,但我认为你可以自己管理它。

+0

比regex,IMO更整洁,更可读。 – anaximander 2013-05-14 08:46:43

+1

谢谢:)我喜欢正则表达式,但有许多情况下你可以不用,最终得到更多更干净的代码。有些人似乎将它们用作一切的解决方案,所以我试图证明大多数问题都可以通过简单的字符串操作来解决。 – pyrocumulus 2013-05-14 09:11:26

0

这里有一个正则表达式的例子,这是否和团体通过你所需要的:

/s:([^ ]{1,100}) /e:([^ ]{1,100}) /f:([^ ]{1,100}) 

此外,我推荐使用http://regexpal.com/学习如何创建这些。

编辑:这是一个非常具体的例子,没有涵盖所有可能的情况。在上面的网站中对不同的输入进行测试以进行必要的更改。

0

你需要3个不同的正则表达式(至少我找不到常见的一个)这个过程。因为http://摧毁这种情况下每一个正则表达式:)

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

输出将是;

http://asdasd.asd 
device 
create 

这是DEMO

0

一个更简单的解决办法是:

(?<=\:)[^ ]+ 

这种单一的正则表达式将返回三组。