简体   繁体   中英

Parse key=value with regular expression

I have simple text:

first_name=value1
secon_name=value2
date_b = 12.01.1989

Rows is separated by \\n char. I have code which split this string and then I iterate through array and check the keys:

string[] data = str.Split('\n');
foreach (var row in data)
{
   if (row.StartsWith("first_name"))
   {
       obj.FirstName = row.Remove(0, ("first_name").Length);
       ...
   }
}

But there are about 15 pairs and the code in foreach very unreadable. How to parse this with regular expression? I want to get dictionary<key, value> .

PS. Some rules:
1. The key is without whitespace.
2. The value can contain whitespace.

(.*?)\s*=\s*([^\s]+)

This should work.Will give you groups containing both the matches.

Have a look.

http://regex101.com/r/wE3dU7/4

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