I’m grabbing values from a grails select tag, and need to strip out the extra characters that jQuery is grabbing and format the string before passing it off to our BIRT report server.
The list from grails looks something like:
Term:
[201360, Continuing Ed Automn 2013]
[201350, Summer Session 2013]
...
College
[AS, College of Arts and Sciences]
[BA, College of Business Administration]
...
This is an example of what is being serialized by jQuery when a selection is made on both of the select lists:
Term=%5B201360%2C+Continuing+Ed+Autumn+2013%5D&College=%5BBA%2C+School+of+Business+Admin%5D
I would like to have the final value be something like
Term=201360&College=BA
The problem with doing a straight substring is the number of variables can change, and either are optional. There could be 1, or there could be 20.
How would I go about extracting only the needed pieces?
I am not sure why you end up with that kind of data. Anyway:
The regex may look slightly more complex than necessary, but I remove extra leading and trailing spaces, if any, in the first item inside
[].Explanation:
key=[item1, item2, ...]. It will capture the first item and throw away the rest.\[and\]are literal[and]characters.*([^,]+?) *,: Eat up leading space*. Then consume and capture the token([^,]+?), assumed to have no comma[^,], and due to the lazy quantifier+?will consume as little as possible before encountering the sequence: optional space followed by (the first) comma*,.[^\]]+: Consume (and later throw away) everything that is not]. It will stop at](or end of string, but not the case here).Assumptions:
[]are balanced, and there are no nesting.,inside the items to be extracted.key=[item1, item2, ...]