7

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!

Ted
  • 3,805
  • 14
  • 56
  • 98

5 Answers5

22
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 {}
msk
  • 8,885
  • 6
  • 41
  • 72
1

See the docs for NSRegularExpression

In particular the section titled Replacing Strings Using Regular Expressions

borrrden
  • 33,256
  • 8
  • 74
  • 109
1

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
}
larva
  • 4,687
  • 1
  • 24
  • 44
0

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.

Pfitz
  • 7,336
  • 4
  • 38
  • 51
  • 1
    Just one thing to beware, this will only work if the numbers are on the edges (i.e. XXX123 or 123XXX will work, but not XX123XX). For the information given this answer works perfectly, but I thought I'd chime in anyway in case OP has other sets. – borrrden Jul 10 '12 at 09:52
  • you are right - added information to my answer to clarifie it! – Pfitz Jul 10 '12 at 09:54
0

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

Damien Locque
  • 1,810
  • 2
  • 20
  • 42