MSLibrary. SIMPLY: remove unnecessary characters from the string using regular expressions for iOS and more ...
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