Reputation: 677
I have a NSString in this format:
"Key1-Value1,Key2-Value2,Key3-Value3,..."
I need only keys (with a space after every comma):
Key1, Key2, Key3, etc.
I thought to create an array of components from the string using the comma as separator, and after, for every component, extract all characters since the "-"; then I'd serialize the array elements. But I fear this could be very heavy about performances.
Do you know a way to do this using regular expressions?
Upvotes: 1
Views: 1890
Reputation: 57169
The regex will greatly depend on the data you are using. For example if the key or value is allowed to be all numbers, or allowed to contain space and punctuation, you would need to modify the regex. For your current example however this will work.
NSString *example = @"Key1-Value1,Key2-Value2,Key3-Value3,...";
NSString *result = [example stringByReplacingOccurrencesOfString:@"(\\w+)-(\\w+),?"
withString:@"$1, "
options:NSRegularExpressionSearch
range:NSMakeRange(0, [example length])];
result = [result stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@", "]];
NSLog(@"%@", result);
Upvotes: 2