Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 @"";

like image 942
Faz Ya Avatar asked Mar 12 '12 04:03

Faz Ya


1 Answers

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); 
like image 185
neevek Avatar answered Oct 17 '22 10:10

neevek