C#Regex.Split和正则表达式

时间:2012-02-13 17:20:21

标签: c# guid

我有字符串,我需要拆分它两次并选择追求特殊字符的部分。

让我们说:

string myString = "Word 2010|82e146e7-bc85-4bd4-a691-23d55c686f4b;#Videos|55140947-00d0-4d75-9b5c-00d8d5ab8436";

string[] guids = Regex.Split(myString,";#");

所以这里我得到了两个带有Value + GUID元素的数组。但我只需要Guids,比如:

  

[0] 82e146e7-bc85-4bd4-a691-23d55c686f4b

     

[1] 55140947-00d0-4d75-9b5c-00d8d5ab8436

以一两行的方式做任何事情?

5 个答案:

答案 0 :(得分:5)

你可以做到这一点,但仅仅因为可以在一行中完成它并不意味着你应该(如果你在这里过于花哨,可读性就起作用了)。显然,这里根本没有验证。

string myString = "Word 2010|82e146e7-bc85-4bd4-a691-23d55c686f4b;#Videos|55140947-00d0-4d75-9b5c-00d8d5ab8436";

string[] guids = Regex.Split(myString, ";#")
                      .SelectMany(s => Regex.Split(s, @"\|").Skip(1))
                      .ToArray();

Assert.AreEqual(2, guids.Length);
Assert.AreEqual("82e146e7-bc85-4bd4-a691-23d55c686f4b", guids[0]);
Assert.AreEqual("55140947-00d0-4d75-9b5c-00d8d5ab8436", guids[1]);

答案 1 :(得分:3)

如果每个的最后一部分始终是一个guid,你可以在没有正则表达式的情况下轻松完成:

string[] guids = String.Split(";").Select(c => c.Substring(c.Length - 36)).ToArray();

答案 2 :(得分:0)

string[] guids = myString.Split(';').Select(x => x.Split('|')[1]).ToArray();

答案 3 :(得分:0)

string myString = "Word 2010|82e146e7-bc85-4bd4-a691-23d55c686f4b;#Videos|55140947-00d0-4d75-9b5c-00d8d5ab8436";

//split the string by ";#"
string[] results = myString.Split(new string[] { ";#" }, StringSplitOptions.RemoveEmptyEntries);

//remove the "value|" part
results[0] = results[0].Substring(results[0].IndexOf('|') + 1);
results[1] = results[1].Substring(results[1].IndexOf('|') + 1);

//Same as above, but in a for loop. usefull if there are more then 2 guids to find
//for(int i = 0; i < results.Length; i++)
//  results[i] = results[i].Substring(results[i].IndexOf('|') + 1);

foreach(string result in results)
    Console.WriteLine(result);

答案 4 :(得分:0)

var guids = Regex
    .Matches(myString, @"HEX{8}-HEX{4}-HEX{4}-HEX{4}-HEX{12}".Replace("HEX", "[A-Fa-f0-9]"))
    .Cast<Match>()
    .Select(m => m.Value)
    .ToArray();