Need to separate a string on & but not on &.
Is there a more elegant way to code this up rather than just replacing it first then separating it on the &? Like this...
query = [query stringByReplacingOccurrencesOfString:@"&" withString:@"~~~"];
NSArray * kvpairs = [query componentsSeparatedByString:@"&"];
NSMutableArray *mArr = [[NSMutableArray alloc] init];
for (NSString *kvp in kvpairs) {
[mArr addObject:[kvp stringByReplacingOccurrencesOfString:@"~~~" withString:@"&"]];
}
kvpairs = [NSArray arrayWithArray:mArr];
[mArr release];
You could use NSRegularExpression to enumerate through the string on a regular expression that matches & but not &, e.g.: @"&(?!amp;)". This will be more cumbersome than your current method but more exact, because it will work without modifying the original string and doesn't rely on a token value.
If you control the input to this method and can guarantee that ~~~ won't appear normally, there's nothing wrong with using ~~~. However if you don't control the input then you should attempt to parse the string without modification.
There isn't really anything wrong with that, as long as you are 100% sure that the string ~~~ won't occur in your query.
If you are not, my next step would be to implement a method to parse the string into an array. In this method, you could find each &, then check if it is followed by amp;. If it is, move on to the next one, if it is not, cut the string there and repeat.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With