Use regular expression to find/replace substring in NSString
Asked Answered
O

2

64

I would like to use regular expression to find every instances of a regular expression pattern I.e. &*; in my string and remove that from so the return value is the original string without any of the matches. Also would like to use the same function to match multiple spaces between words and have a single space instead. Could not find such a function.

Sample input string

NSString *str = @"123 &1245; Ross Test  12";

Return value should be

123 Ross Test 12

If anything matching this pattern "&* or multiple white spaces and replaces it with @"";

Ogilvy answered 12/3, 2012 at 4:18 Comment(0)
E
163
NSString *string = @"123 &1245; Ross Test 12";
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"&[^;]*;" options:NSRegularExpressionCaseInsensitive error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
NSLog(@"%@", modifiedString);
Eucaine answered 12/3, 2012 at 4:32 Comment(1)
In ObjC you should use nil instead of NULL. But NULL works too, since it is C.Championship
O
14

String replacing code using regex in String extension

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

resolve

NSString *string = @"123 &1245; Ross Test  12";
// remove all matches string
NSString *result = [string replacingWithPattern:@"&[\\d]+?;" withTemplate:@"" error:nil];
// result = "123  Ross Test  12"

or more

NSString *string = @"123 +   456";
// swap number
NSString *result = [string replacingWithPattern:@"([\\d]+)[ \\+]+([\\d]+)" withTemplate:@"$2 + $1" error:nil];
// result = 456 + 123

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

use

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 {
    // error
}
// result = "I want to remove all digit and a char right after from string"
Omnirange answered 8/7, 2016 at 8:59 Comment(2)
Would be better rename function name to - (NSString *)stringByReplacingWithPattern:(NSString *)pattern withTemplate:(NSString *)withTemplate error:(NSError **)errorVedetta
would be better to remove all those withGoldarned

© 2022 - 2024 — McMap. All rights reserved.