regular expressions replace in iOS

Ted picture Ted · Jul 10, 2012 · Viewed 9.9k times · Source

I am going to need to replace a dirty string for a clean string:

-(void)setTheFilter:(NSString*)filter
{
    [filter retain];
    [_theFilter release];

    <PSEUDO CODE>
    tmp = preg_replace(@"/[0-9]/",@"",filter);
    <~PSEUDO CODE>

    _theFilter = tmp;
}

This should eliminate all numbers in the filter so that:

@"Import6652"
would yield @"Import"

How can I do it in iOS ?

Thanks!

Answer

msk picture msk · Jul 10, 2012
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:
                              @"([0-9]+)" options:0 error:nil];

[regex replaceMatchesInString:str options:0 range:NSMakeRange(0, [str length]) withTemplate:@""];

Swift

do {
    let regex = try NSRegularExpression(pattern: "([0-9]+)", options: NSRegularExpressionOptions.CaseInsensitive)
    regex.replaceMatchesInString(str, options: NSMatchingOptions.ReportProgress, range: NSRange(0,str.characters.count), withTemplate: "")
} catch {}