使用正则表达式在字符串扩展中进行字符串替换的代码
Objective-C
@implementation NSString(RegularExpression)
- (NSString *)replacingWithPattern:(NSString *)pattern withTemplate:(NSString *)withTemplate error:(NSError **)error {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:error];
return [regex stringByReplacingMatchesInString:self
options:0
range:NSMakeRange(0, self.length)
withTemplate:withTemplate];
}
@end
解决
NSString *string = @"123 &1245; Ross Test 12";
NSString *result = [string replacingWithPattern:@"&[\\d]+?;" withTemplate:@"" error:nil];
或更多
NSString *string = @"123 + 456";
NSString *result = [string replacingWithPattern:@"([\\d]+)[ \\+]+([\\d]+)" withTemplate:@"$2 + $1" error:nil];
Swift2
extension String {
func replacing(pattern: String, withTemplate: String) throws -> String {
let regex = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
return regex.stringByReplacingMatchesInString(self, options: [], range: NSRange(0..<self.utf16.count), withTemplate: withTemplate)
}
}
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)
}
}
var string = "1!I 2\"want 3#to 4$remove 5%all 6&digit and a char right after 7'from 8(string"
do {
let result = try string.replacing("[\\d]+.", withTemplate: "")
} catch {
}