Reputation: 305
Is there any method or library with function that allows to perform such parsing from string: Input: input string, in which I want to search, pattern for search (will describe later). Output: array of strings
The pattern must be in format like:
"Items: {0} in Boxes: {1}"
So you should specify the places where output values must be.
Input and output examples using this pattern:
Input: "Items Item 1, Item 2 in Boxes Box 1, Box 2"
Output: ["Item 1, Item 2", "Box 1, Box 2"]
I know that this is not a hard function to write, but I'm searching for a existed solution in a standard .NET library or for a custom and fast solution instead.
Upvotes: 1
Views: 266
Reputation: 1904
There are 2 solutions I can think of: Using Regex
or using String
manipulation functions.
First approach with regex:
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
Solution with classical string operations:
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(',');
Take care of the spaces left here, you still need to .Trim()
the items.
What you use and what fits your problem best depends on the circumstances. I'd prefer the string solution as it's more readable and less error prone.
Upvotes: 1