Use regular expression to find/replace substring in NSString

Faz Ya picture Faz Ya · Mar 12, 2012 · Viewed 54.1k times · Source

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

neevek picture neevek · Mar 12, 2012
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);