regular expressions replace in iOS
10,057
Solution 1
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 {}
Solution 2
See the docs for NSRegularExpression
In particular the section titled Replacing Strings Using Regular Expressions
Solution 3
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
}
Author by
Ted
Updated on July 12, 2022Comments
-
Ted almost 2 years
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!