Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular expressions replace in iOS

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!

like image 980
Ted Avatar asked Jul 10 '12 09:07

Ted


People also ask

Can you replace with regex?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

How do I replace words in Xcode?

Press ⌃ ⇧ R to open the Replace in Path dialog. In the top field, enter your search string. In the bottom field, enter your replacement string.

What is $1 in regex replace?

$1 is the first group from your regular expression, $2 is the second. Groups are defined by brackets, so your first group ($1) is whatever is matched by (\d+). You'll need to do some reading up on regular expressions to understand what that matches.

What are regular expressions in iOS?

A regex ( also known as regular expressions) is a pattern string. These pattern strings allow you to search specific patterns in documents and to validate email, phone number etc. In iOS and MacOS regex been handled by NSRegularExpression . To know more about NSRegularExpression read apple documentation.


1 Answers

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 {}
like image 79
msk Avatar answered Sep 21 '22 07:09

msk