Reputation: 132
How can I use Regular Expressions to split this string
String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";
into a list like below:
name1 smith ben
name2 Test
abcd Test=
mmmm Test=`
It is similar to getting attributes from an element but not quite.
Upvotes: 0
Views: 62
Reputation: 196
The first thing to do is remove the brackets and 'TEST' part from the string so you are just left with the keys and values. Then you can split it (based on '\"') into an array, where the odd entries will be the keys, and the even entries will be the values. After that, it's easy enough to populate your list:
String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";
SortedList<string, string> list = new SortedList<string, string>();
//Remove the start and end tags
s = s.Remove(0, s.IndexOf(' '));
s = s.Remove(s.LastIndexOf('\"') + 1);
//Split the string
string[] pairs = s.Split(new char[] { '\"' }, StringSplitOptions.None);
//Add each pair to the list
for (int i = 0; i+1 < pairs.Length; i += 2)
{
string left = pairs[i].TrimEnd('=', ' ');
string right = pairs[i+1].Trim('\"');
list.Add(left, right);
}
Upvotes: 2