ikkarion ikkarion - 1 year ago 60
iOS Question

How to write regular expression with global search in iOS?

I'm trying to create a regular expression for reduce the state name in an abbreviation. For example, the string "New York" should be replaced with "NY".

I came with this

. I tested it here: http://regexr.com and it works!

When I write that in objective-c code it does not work.

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^A-Z]/g" options:NSRegularExpressionCaseInsensitive error:&error];

NSString *abbreviation = [regex stringByReplacingMatchesInString:self.state options:0 range:NSMakeRange(0, [self.state length]) withTemplate:@""];

I'm not very experienced with regular expressions. Why is that not working?
(It can be a dumb mistake, but I can`t find it)

Answer Source

what is \g in regex? try @"[^A-Z]" or @"[^A-Z]+" with options 0:

in iOS using regex to search or replace is really greedy, searching or replacing scopes is depend on range in regex function's parameters.

NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"[^A-Z]" options:0 error:&error]; // or @"[^A-Z]+"

NSString *UF = [regex stringByReplacingMatchesInString:@"New York" options:0 range:NSMakeRange(0, [@"New York" length]) withTemplate:@""];