开发者

RegEx groups in C#

开发者 https://www.devze.com 2023-03-30 21:11 出处:网络
I have string with product information and I would like to parse that string and read the pr开发者_如何学编程oduct information.

I have string with product information and I would like to parse that string and read the pr开发者_如何学编程oduct 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消