Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSString componentsSeparatedByString "&" but ignore "& amp;"

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];
like image 620
tdios Avatar asked Jul 11 '26 00:07

tdios


2 Answers

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.

like image 168
dreamlax Avatar answered Jul 13 '26 14:07

dreamlax


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.

like image 44
Simon Goldeen Avatar answered Jul 13 '26 13:07

Simon Goldeen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!