如何拆分字符串,接收异常

时间:2013-12-06 20:13:35

标签: c#

有这样的问题&我有两个字符串:

a@site.ru:bvxb02lt;mu:10
b@site.ru:abc;ewfewf;tu:10

如何以这种方式用1个函数分割每个字符串:

string a1 = a@site.ru
string a2 = bvxb02lt
string a3 = mu
string a4 = 10

string b1 = b@site.ru
string b2 = abc
string b3 = ewfewf;tu
string b4 = 10

我试过了:

string login = a.Trim().Split(';')[0].Split(':')[0].Trim();
string pwd = a.Trim().Split(';')[0].Split(':')[1].Trim();
string domain = a.Trim().Split(';')[1].Split(':')[0].Trim();
string limits = a.Trim().Split(';')[1].Split(':')[1].Trim(); // but here in second string I receive exception that Index was outside the bounds of the array.

3 个答案:

答案 0 :(得分:5)

使用此正则表达式,您可以这样做:

(.*):(.*?);(.*):(.*)

所以在代码中你会做这样的事情:

var matches = Regex.Match(input, pattern);

这是Regex 101 to prove it

答案 1 :(得分:2)

使用字符数组重载来分割它们。

void Main()
{
    string input = "a@site.ru:bvxb02lt;mu:10";
    var tokens = input.Split(new char[] {':', ';' });
    Console.WriteLine (tokens);
}

输出:

  

a@site.ru
  bvxb02lt
  亩
  10

答案 2 :(得分:1)

拆分两次

static void Main(string[] args)
{
    string[] strs = new string[]
    {
        "a@site.ru:bvxb02lt;mu:10",
        "b@site.ru:abc;ewfewf;tu:10"
    };

    foreach (var str in strs)
    {
        // 0: login 1: password & domain 2: limits
        var pieces = str.Split(new char[] { ':' });

        string login = pieces[0];
        string limits = pieces[2];

        // Split password & domain (only at the first `;`)
        var innerPieces = pieces[1].Split(new char[] { ';' }, 2);

        string password = innerPieces[0];
        string domain = innerPieces[1];
    }
}

输出

a@site.ru
bvxb02lt
mu
10

b@site.ru
abc
ewfewf;tu
10