我能想到两种解决方案:使用Regex 或使用String 操作函数。
正则表达式的第一种方法:
string text = "Items Item 1, Item 2 in Boxes Box 1, Box 2";
var match = Regex.Match(text, "^Items(?: ([^,]*),?)* in Boxes(?: ([^,]*),?)*$");
System.Console.WriteLine("Items:");
foreach (Capture cap in match.Groups[1].Captures)
System.Console.WriteLine(cap.Value); // -->Item1 and Item2
System.Console.WriteLine("Boxes:");
foreach (Capture cap in match.Groups[2].Captures)
System.Console.WriteLine(cap.Value); // --> Box 1 and Box 2
经典字符串操作的解决方案:
string text = "Items Item 1, Item 2 in Boxes Box 1, Box 2";
var allItems = text.Remove(text.IndexOf("in Boxes")).Remove(0, "Items ".Length);
var itemArray = allItems.Split(',');
var allBoyes = text.Remove(0, text.IndexOf("in Boxes")).Remove(0, "in Boxes ".Length);
var boxArray= allItems.Split(',');
照顾好这里留下的空间,你仍然需要.Trim()这些物品。
您使用什么以及最适合您的问题取决于具体情况。我更喜欢字符串解决方案,因为它更具可读性且不易出错。