简体   繁体   中英

RegEx groups in C#

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM