문제

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top