简体   繁体   English

C#中的RegEx组

[英]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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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