前言
有時我們需要在一大段長文本中過濾出我們需要的字段,或者檢驗該文本是否符合要求(該文本是否是郵箱,鏈接,電話號碼或身份證),這時候就需要用到正則表達式了,iOS中也加入了相關的類來支持正則表達式的使用。本文詳細介紹了關于iOS正則表達式運用的相關內容,分享出來供大家參考學習,下面話不多說了,來一起看看詳細的介紹吧。
一、NSRegularExpression
1. 正則表達式的創建
+ (nullable NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;- (nullable instancetype)initWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error
該類中的屬性
options 定義的枚舉類型如下:
typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) { NSRegularExpressionCaseInsensitive = 1 << 0, //不區分大小寫的 NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1, //忽略空格和# - NSRegularExpressionIgnoreMetacharacters = 1 << 2, //整體化 NSRegularExpressionDotMatchesLineSeparators = 1 << 3, //匹配任何字符,包括行分隔符 NSRegularExpressionAnchorsMatchLines = 1 << 4, //允許^和$在匹配的開始和結束行 NSRegularExpressionUseUnixLineSeparators = 1 << 5, //(查找范圍為整個無效) NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6 //(查找范圍為整個無效) };
2. 搜索字符串
//枚舉允許Block處理每個正則表達式匹配的字符串- (void)enumerateMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range usingBlock:(void (NS_NOESCAPE ^)(NSTextCheckingResult * _Nullable result, NSMatchingFlags flags, BOOL *stop))block;//返回一個數組,包含字符串中正則表達式的所有匹配項- (NSArray<NSTextCheckingResult *> *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;//返回字符串指定范圍內匹配數- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;//返回字符串指定范圍內第一個匹配項。- (nullable NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;//返回字符串指定范圍內第一個匹配的范圍- (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
NSMatchingOptions的定義如下:
typedef NS_OPTIONS(NSUInteger, NSMatchingOptions) { NSMatchingReportProgress = 1 << 0, /* 在長時間運行的匹配操作中定期調用Block */ NSMatchingReportCompletion = 1 << 1, /* 完成任何匹配后,調用Block一次*/ NSMatchingAnchored = 1 << 2, /*指定匹配僅限于搜索范圍開始時的匹配 */ NSMatchingWithTransparentBounds = 1 << 3, /* 定匹配可以檢查超出搜索范圍的范圍的字符串的部分,以用于諸如字邊界檢測,前瞻等。如果搜索范圍包含整個字符串,該常量將不起作用 */ NSMatchingWithoutAnchoringBounds = 1 << 4 /* 指定^并且$不會自動匹配搜索范圍的開始和結束,但仍將與整個字符串的開頭和結尾相匹配。如果搜索范圍包含整個字符串,則該常量不起作用 */};
3.替換字符串
//返回與模板字符串替換的匹配正則表達式的新字符串- (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;//自定義替換功能- (NSString *)replacementStringForResult:(NSTextCheckingResult *)result inString:(NSString *)string offset:(NSInteger)offset template:(NSString *)templ;//通過根據需要添加反斜杠轉義來返回模板字符串,以保護符合模式元字符的任何字符+ (NSString *)escapedTemplateForString:(NSString *)string;
使用示例
NSString *str = @"aabbcccdeaargdo14141214aaghfh56821d3gad4"; NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"aa" options:NSRegularExpressionCaseInsensitive error:NULL]; if (expression != nil) { //匹配到的第一組 NSTextCheckingResult *firstMatch = [expression firstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)]; NSRange range = [firstMatch rangeAtIndex:0]; NSString *result = [str substringWithRange:range]; NSLog(@"匹配到的第一組:%@",result); //匹配到的個數 NSInteger number = [expression numberOfMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)]; NSLog(@"匹配到的個數%ld",number); //配到到的所有數據 NSArray *allMatch = [expression matchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)]; for (int i = 0; i < allMatch.count; i ++) { NSTextCheckingResult *matchItem = allMatch[i]; NSRange range = [matchItem rangeAtIndex:0]; NSString *result = [str substringWithRange:range]; NSLog(@"匹配到的數據:%@",result); } //匹配到第一組的位置 NSRange firstRange = [expression rangeOfFirstMatchInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length)]; NSLog(@"匹配到第一組的位置:開始位置%lu--長度%lu",(unsigned long)firstRange.location,(unsigned long)firstRange.length); //替換字符串 NSString *resultStr = [expression stringByReplacingMatchesInString:str options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@"bbbb"]; NSLog(@"替換后的字符串:%@",resultStr); NSInteger resultNum = [expression replaceMatchesInString:[str mutableCopy] options:NSMatchingReportProgress range:NSMakeRange(0, str.length) withTemplate:@"bbbb"]; NSLog(@"替換的個數;%ld",(long)resultNum); }打印log:2017-08-13 23:28:53.898 NSRegularExpressionDemo[82046:8220904] 匹配到的第一組:aaNSRegularExpressionDemo[82046:8220904] 匹配到的個數3NSRegularExpressionDemo[82046:8220904] 匹配到的數據:aaNSRegularExpressionDemo[82046:8220904] 匹配到的數據:aaNSRegularExpressionDemo[82046:8220904] 匹配到的數據:aaNSRegularExpressionDemo[82046:8220904] 匹配到第一組的位置:開始位置0--長度2NSRegularExpressionDemo[82046:8220904] 替換后的字符串:bbbbbbcccdebbbbrgdo14141214bbbbghfh56821d3gad4NSRegularExpressionDemo[82046:8220904] 替換的個數;3
二、字符串
//NSStringCompareOptions --> NSRegularExpressionSearch- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask;- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch;- (NSRange)rangeOfString:(NSString *)searchString options:(NSStringCompareOptions)mask range:(NSRange)rangeOfReceiverToSearch locale:(nullable NSLocale *)locale
從上面的api可以看出,只能匹配到第一組
使用示例
NSString *str = @"aabbcccdeaargdo14141214aaghfh56821d3gad4"; NSRange strMatchStr = [str rangeOfString:@"aa" options:NSRegularExpressionSearch]; NSLog(@"匹配到字符串的位置:開始位置%lu--長度%lu",(unsigned long)strMatchStr.location,(unsigned long)strMatchStr.length)打印log:NSRegularExpressionDemo[82080:8224265] 匹配到字符串的位置:開始位置0--長度2
三、謂詞
使用示例
NSString *str2 = @"aabbcc"; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",@"^aa(.)*cc$"]; BOOL isMatch = [predicate evaluateWithObject:str2]; NSLog(@"匹配的結果:%d",isMatch);打印log:NSRegularExpressionDemo[82679:8253019] 匹配的結果:1
四、正則表達式
可以參考這篇文章:http://www.49028c.com/article/73342.htm
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對武林網的支持。
新聞熱點
疑難解答