Back to Home

MSLibrary. SIMPLY: remove unnecessary characters from the string using regular expressions for iOS and more ...

regular expressions · enumerations · enum · binary numbers · binary operations · application development · iOS development · web development · iOS library · iOS libraries

MSLibrary. SIMPLY: remove unnecessary characters from the string using regular expressions for iOS and more ...

    In addition to the large and detailed materials, the developers of the MSLibrary for iOS library decided to start a series of very compact articles on how to SIMPLY implement a particular function. No theory, just practice ...

    So, we remove unnecessary characters from the string using regular expressions using a simple function:

    NSString *yourFuncionName(NSString *string) {
        NSString *regExString = @"yourRegularExpression";
        NSRegularExpression *_regEx = [NSRegularExpression regularExpressionWithPattern:regExString options:NSRegularExpressionCaseInsensitive error:nil];
        return [_regEx stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
    }
    

    That's all, actually, it remains to choose a suitable regular expression that solves your problems.

    Some useful regular expressions:

        \\ s - removes all spaces
        [-: _ \\.] - removes all characters in square brackets
        [: ^ digit:] - leaves only numbers
        [: ^ alpha:] - leaves only letters
        [: ^ alnum:] - leaves only letters and numbers
        [: ^ word:] - leaves only letters, numbers and underscores
    

    Important: do not forget to escape all meta-characters in the regular expressions with the sign "\\"

    For those who are just mastering work skills, we give an example of a code that leaves only numbers in a line:

    NSString *function_OnlyDigitsInString(NSString *string) {
        NSString *regExString = @"[:^digit:]";
        NSRegularExpression *_regEx = [NSRegularExpression regularExpressionWithPattern:regExString options:NSRegularExpressionCaseInsensitive error:nil];
        return [_regEx stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0, [string length]) withTemplate:@""];
    }
    


    As you can see, the question is solved in just a few simple lines of code, and when using the MSLibrary for iOS library - in one line.



    We hope that the material was useful to you, the MSLibrary for iOS team

    Other articles: Capturing and verifying phone numbers using regular expressions, for iOS and more ... Part 1 Capturing and verifying phone numbers using regular expressions, for iOS and more ... Part 2 Implementation of multiple choice of conditions using bit masks, for iOS and not only ... Creation and compilation of cross-platform (universal) libraries in Xcode



    Read Next