iOS原生自帶正則校驗工具介紹

在以前做開發(fā)時,對于正則效驗一般喜歡用三方開源庫RegexKitLite去處理,因為它高效而且簡單兼容性強,一行代碼即可完成查詢,但是它的誕生至今已經快10年了,現(xiàn)在就連作者的開發(fā)文檔也已經移除了:https://regexkit.svn.sourceforge.net/svnroot/regexkit/RegexKitLite@69
所以它基本可以離開歷史的舞臺了。

現(xiàn)在研究了下iOS原生的處理工具,發(fā)現(xiàn)還是挺好用的。
iOS原生用來做正則校驗的有兩個類 NSPredicate 和 NSRegularExpression:

NSPredicate是謂詞對象過濾,查詢比較簡單

如手機號碼驗證

  • (BOOL) validateMobile:(NSString *)mobile
    {
    //手機號以13, 15,18開頭,八個 \d 數(shù)字字符
    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;

返回所有匹配結果的集合(適合,從一段字符串中提取我們想要匹配的所有數(shù)據(jù))

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

返回正確匹配的個數(shù)(通過等于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;

它可以根據(jù)查詢條件對不可變字符串和可變字符串進行替換:

  • (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也挺不錯的,高效安全!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 原文: NSRegular?Expression 原作者:Nate Cook 遇到問題,哦,要用NSRegular...
    BoxDeng閱讀 1,698評論 0 1
  • 前言 最先接觸編程的知識是在大學里面,大學里面學了一些基礎的知識,c語言,java語言,單片機的匯編語言等;大學畢...
    oceanfive閱讀 3,395評論 0 7
  • iOS中有三種實現(xiàn)正則表達式的匹配: 1.利用NSPredicate(謂詞)匹配; 2.利用rangeOfStri...
    馬小悅閱讀 1,410評論 1 0
  • 由于目前開發(fā)的項目中很多的表單提交并且上一次也介紹了我們項目中的表單組件封裝,但是表單中有很多的字段控制,比如只能...
    天一呀閱讀 680評論 1 0
  • 由于目前開發(fā)的項目中很多的表單提交并且上一次也介紹了我們項目中的表單組件封裝,但是表單中有很多的字段控制,比如只能...
    yoku醬閱讀 355評論 0 3

友情鏈接更多精彩內容