Ted
Ted

Reputation: 3875

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!

Upvotes: 7

Views: 10408

Answers (5)

larva
larva

Reputation: 5148

String replacing code using regex

Swift3

extension String {
    func replacing(pattern: String, withTemplate: String) throws -> String {
        let regex = try RegularExpression(pattern: pattern, options: .caseInsensitive)
        return regex.stringByReplacingMatches(in: self, options: [], range: NSRange(0..<self.utf16.count), withTemplate: withTemplate)
    }
}

use

var string: String = "Import6652"
do {
    let result = try string.replacing(pattern: "[\\d]+", withTemplate: "")
} catch {
    // error
}

Upvotes: 1

msk
msk

Reputation: 8905

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 {}

Upvotes: 22

Pfitz
Pfitz

Reputation: 7344

Though not via a regular expression but you can use stringByTrimmingCharactersInSet

stringByTrimmingCharactersInSet:
Returns a new string made by removing from both ends of the receiver characters contained in a given character set.

in combination with

decimalDigitCharacterSet
Returns a character set containing the characters in the category of Decimal Numbers.

like this:

[filter stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];

Caveat: it will only remove the characters at both ends.

Upvotes: 0

Damien Locque
Damien Locque

Reputation: 1809

in iOS 4.0+, you can use NSRegularExpression:

Use matchesInString:options:range: to get an array of all the matching results.

and then delete them from original string

Upvotes: 0

borrrden
borrrden

Reputation: 33421

See the docs for NSRegularExpression

In particular the section titled Replacing Strings Using Regular Expressions

Upvotes: 1

Related Questions