Domanda

I have string with product information and I would like to parse that string and read the product information.

My string look like this:

ID: 1
NAME: Product name
INFORMATION: Here goes the information about a product 
STATUS: Available

I would like to parse this text in this way:

string id = product id;
string name = product name;
string info = product information; 
string available = product availability; 

How can I accomplish that. I know it's possible with groups but I'm stuck and don't how do that.

Thanks in advance.

È stato utile?

Soluzione

You can parse the data quite easily, for example, to a dictionary. Note that you don't really need a regex here, this is even nicer without one:

var values  = data.Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)
                  .Select(line => line.Split(":".ToCharArray(), 2))
                  .ToDictionary(pair => pair[0], pair => pair[1], 
                                StringComparer.OrdinalIgnoreCase);
string name = values["name"];

A regex option, with some space trimming:

var values = Regex.Matches(data, @"^(?<Key>\w+)\s*:\s*(?<Value>.*?)\s*$", RegexOptions.Multiline)
                  .Cast<Match>()
                  .ToDictionary(m => m.Groups["Key"].Value,
                                m => m.Groups["Value"].Value,
                                StringComparer.OrdinalIgnoreCase);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top