iOS原生自带正则校验工具介绍

在以前做开发时,对于正则效验一般喜欢用三方开源库RegexKitLite去处理,因为它高效而且简单兼容性强,一行代码即可完成查询,但是它的诞生至今已经快10年了,现在就连作者的开发文档也已经移除了:https://regexkit.svn.sourceforge.net/svnroot/regexkit/RegexKitLite@69
所以它基本可以离开历史的舞台了。

现在研究了下iOS原生的处理工具,发现还是挺好用的。
iOS原生用来做正则校验的有两个类 NSPredicate 和 NSRegularExpression:

NSPredicate是谓词对象过滤,查询比较简单

如手机号码验证

  • (BOOL) validateMobile:(NSString *)mobile
    {
    //手机号以13, 15,18开头,八个 \d 数字字符
    NSString *phoneRegex = @"((13[0-9])|(15[4,\D])|(18[0,0-9]))\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
    }

官方对其的解释如下:
The NSPredicate class is used to define logical conditions used to constrain a search either for a fetch or for in-memory filtering.

Predicates represent logical conditions, which you can use to filter collections of objects.
也就是说NSPredicate相对比较简单轻量级,一般用于定义逻辑条件查询,最佳使用场景是使用这些逻辑条件过滤对象集合。

但是比较NSRegularExpression来说,NSRegularExpression的功能性就强大了多了。

今天都重点介绍下NSRegularExpression

官方对其的解释如下:
The fundamental matching method for NSRegularExpression is a Block iterator method that allows clients to supply a Block object which will be invoked each time the regular expression matches a portion of the target string. There are additional convenience methods for returning all the matches as an array, the total number of matches, the first match, and the range of the first match
具体说,它就是iOS纯正的处理正则表达式的类,它可以按照正则表达式去进行复杂的处理:

block方法回调

  • (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range usingBlock:(void (NS_NOESCAPE ^)(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL *stop))block;

返回所有匹配结果的集合(适合,从一段字符串中提取我们想要匹配的所有数据)

  • (NSArray *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

返回正确匹配的个数(通过等于0,来验证邮箱,电话什么的,可以完全代替NSPredicate)

  • (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

返回第一个匹配的结果。注意,匹配的结果保存在 NSTextCheckingResult 类型中

  • (nullable NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

返回第一个正确匹配结果字符串的NSRange

  • (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;

它可以根据查询条件对不可变字符串和可变字符串进行替换:

  • (NSString *)stringByReplacingMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ;
  • (NSUInteger)replaceMatchesInString:(NSMutableString *)string options:(NSMatchingOptions)options range:(NSRange)range withTemplate:(NSString *)templ;

而且甚至还提供了一些简单的正则方法进行处理(包含日期,地址,电话号码检测等):
typedef NS_OPTIONS(uint64_t, NSTextCheckingType) { // a single type
NSTextCheckingTypeOrthography = 1ULL << 0, // language identification
NSTextCheckingTypeSpelling = 1ULL << 1, // spell checking
NSTextCheckingTypeGrammar = 1ULL << 2, // grammar checking
NSTextCheckingTypeDate = 1ULL << 3, // date/time detection
NSTextCheckingTypeAddress = 1ULL << 4, // address detection
NSTextCheckingTypeLink = 1ULL << 5, // link detection
NSTextCheckingTypeQuote = 1ULL << 6, // smart quotes
NSTextCheckingTypeDash = 1ULL << 7, // smart dashes
NSTextCheckingTypeReplacement = 1ULL << 8, // fixed replacements, such as copyright symbol for (c)
NSTextCheckingTypeCorrection = 1ULL << 9, // autocorrection
NSTextCheckingTypeRegularExpression API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)) = 1ULL << 10, // regular expression matches
NSTextCheckingTypePhoneNumber API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)) = 1ULL << 11, // phone number detection
NSTextCheckingTypeTransitInformation API_AVAILABLE(macos(10.7), ios(4.0), watchos(2.0), tvos(9.0)) = 1ULL << 12 // transit (e.g. flight) info detection
}

直接调用原生的枚举即可快速检测

  • (nullable NSDataDetector *)dataDetectorWithTypes:(NSTextCheckingTypes)checkingTypes error:(NSError **)error;

综上所诉,如果进行正则效验,无需再用其他三方库的正则解析器去处理了,其实原生的NSRegularExpression也挺不错的,高效安全!

你可能感兴趣的:(iOS原生自带正则校验工具介绍)