Ben! Its no secret I've always been not too keen on regex, but this is really killing me. I've been reading your regex posts trying to figure how to parse a string just like this: [event=action][id=longuuid][a=b][c=D] and so forth. After a good hour of eye strain and plucking at my keyboard, I thought it might be wise to ask for your help. The best I could come up with was: strData = str.split('\[?\[*\[?\]') which left a much annoying [ at the beginning of each index. At one point I was able to get that [ appear on just the First index, but... thats useless too. Hope you can help, take it easy!
You are on the right track - regular expressions are definitely something that we can use in this situation. The trick here is to see how we can break down the regular expression pattern. As you can see, when we look at your sample data string and abstract it out, what is it? It's really a series of values that match this general pattern:
Now that we have that, what can our name consist of? For the sake of the demo, I am going to say it can consist of any "word" character:
Likewise, I will say that the value will contain every character until the closing bracket:
Now, let's combine all of that into a single regular expression:
When we run this code, we get the output:
event : action
id : longuuid
a : b
c : D
The data string is successfully parsed into a collection of name-value pairs and the output to the screen.
I hope this helps.
Want to use code from this post? Check out the license.