Faz Ya Faz Ya - 1 year ago 123
iOS Question

Use regular expression to find/replace substring in NSString

I would like to use regular expression to find every instances of a regular expression pattern I.e.

in my string and remove that from so the return value is the original string without any of the matches. Also would like to use the same function to match multiple spaces between words and have a single space instead. Could not find such a function.

Sample input string
NSString *str = @"123 &1245; Ross Test 12";

Return value should be
@"123 Ross Test 12";

If anything matching this pattern "&* or multiple white spaces and replaces it with

Answer Source
NSString *string = @"123 &1245; Ross Test 12";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&[^;]*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download