📜 ⬆️ ⬇️

MSLibrary. SIMPLE: remove unnecessary characters from a string using regular expressions for iOS and not only ...

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

So, we remove unnecessary characters from a 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, it remains to find the appropriate regular expression that solves the problems you set.
')
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 screen all meta-characters with "\\" in regular expressions

For those who only master the skills, we will 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 issue 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:
Capture and verify phone numbers using regular expressions, for iOS and not only ... Part 1
Capturing and verifying phone numbers using regular expressions, for iOS and not only ... Part 2
Implementing multiple selection of conditions using bitmasks, for iOS and not only ...
Creating and compiling cross-platform (universal) libraries in Xcode

Source: https://habr.com/ru/post/279563/


All Articles