在實際開發中,我們常常需要用到正則來對一些字符串進行一些操作。如,身份證驗證、手機號驗證、郵箱驗證等。iOS從4.0開始支持正則表達式,并抽象出兩個類來供開發者使用 NSRegularExpression、NSTextCheckingResult。
NSRegularExpression
// 根據所給的正則表達式創建一個NSRegularExpression類的實例,假如正則無效,那么將返回空和error
+ (nullable NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;
- (nullable instancetype)initWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error NS_DESIGNATED_INITIALIZER;
// 一個只讀的正則表達式
@property (readonly, copy) NSString *pattern;
// 正則表達式選項
@property (readonly) NSRegularExpressionOptions options;
// 匹配的個數
@property (readonly) NSUInteger numberOfCaptureGroups;
// 為正則語句每一個匹配類型添加一個'\'
// @"[0-9]{0,}D$" 輸出:\[0-9]\{0,\}D\$
+ (NSString *)escapedPatternForString:(NSString *)string;
NSRegularExpressionOptions
typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) {
// 不區分大小寫
NSRegularExpressionCaseInsensitive = 1 << 0,
// 忽略正則中的空格和‘#-’前綴
NSRegularExpressionAllowCommentsAndWhitespace = 1 << 1,
// 完整的正則,及不做其他處理
NSRegularExpressionIgnoreMetacharacters = 1 << 2,
// 允許‘.’去匹配任意一個字符 ,包括行分隔符'\n'
NSRegularExpressionDotMatchesLineSeparators = 1 << 3,
// 允許‘^’和‘$’匹配開始和結束
NSRegularExpressionAnchorsMatchLines = 1 << 4,
// 設置\n為唯一的行分隔符,否則所有的都有效。
NSRegularExpressionUseUnixLineSeparators = 1 << 5,
// 使用Unicode TR#29標準作為詞的邊界,否則所有傳統正則表達式的詞邊界都有效
NSRegularExpressionUseUnicodeWordBoundaries = 1 << 6
};
NSMatching
typedef NS_OPTIONS(NSUInteger, NSMatchingOptions) {
//找到最長的匹配字符串后調用block回調
NSMatchingReportProgress = 1 << 0,
//找到任何一個匹配串后都回調一次block
NSMatchingReportCompletion = 1 << 1,
//從匹配范圍的開始出進行極限匹配
NSMatchingAnchored = 1 << 2,
//允許匹配的范圍超出設置的范圍
NSMatchingWithTransparentBounds = 1 << 3,
//禁止^和$自動匹配行還是和結束
NSMatchingWithoutAnchoringBounds = 1 << 4
};
typedef NS_OPTIONS(NSUInteger, NSMatchingFlags) {
//匹配到最長串是被設置
NSMatchingProgress = 1 << 0,
//全部分配完成后被設置
NSMatchingCompleted = 1 << 1,
//匹配到設置范圍的末尾時被設置
NSMatchingHitEnd = 1 << 2,
//當前匹配到的字符串在匹配范圍的末尾時被設置
NSMatchingRequiredEnd = 1 << 3,
//由于錯誤導致的匹配失敗時被設置
NSMatchingInternalError = 1 << 4
};
//這個方法會返回一個結果數組,將所有匹配的結果返回
- (NSArray<NSTextCheckingResult *> *)matchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//這個方法會返回匹配到得字符串的個數
- (NSUInteger)numberOfMatchesInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//這個方法會返回第一個查詢到得結果,這個NSTextCheckingResult對象中有一個range屬性,可以得到匹配到的字符串的范圍。
- (nullable NSTextCheckingResult *)firstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
//這個方法直接返回匹配到得范圍,NSRange。
- (NSRange)rangeOfFirstMatchInString:(NSString *)string options:(NSMatchingOptions)options range:(NSRange)range;
NSReplacement
// 獲取替換過的字符串
- (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 *url = @"NSString *url = @"kkkhttp://15215990299www.baidu15530628270.com";";
NSString *regularString = @"\\d{3}-\\d{8}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{4}-\\d{7}|1+[358]+\\d{9}|\\d{8}|\\d{7}";
NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regularString options:0 error:nil];
if (regular) {
NSTextCheckingResult *result = [regular firstMatchInString:url options:NSMatchingReportProgress range:NSMakeRange(0, url.length)];
NSRange range = result.range;
NSLog(@"result 1: %@",[url substringWithRange:range]);
NSArray *arr = [regular matchesInString:url options:NSMatchingReportProgress range:NSMakeRange(0, url.length)];
for (NSTextCheckingResult *result in arr) {
NSLog(@"result >>: %@",[url substringWithRange:result.range]);
}
NSLog(@"%@",[regular stringByReplacingMatchesInString:url options:NSMatchingReportProgress range:NSMakeRange(0, url.length) withTemplate:@"J"]);
NSMutableString *str = [NSMutableString stringWithString:url];
NSLog(@"%ld, %@",[regular replaceMatchesInString:str options:0 range:NSMakeRange(0, url.length) withTemplate:@"J"], str);
}
// 結果
2017-05-11 16:49:15.017 CCZCheckResult[1245:139047] result 1: 15215990299
2017-05-11 16:49:15.018 CCZCheckResult[1245:139047] result >>: 15215990299
2017-05-11 16:49:15.018 CCZCheckResult[1245:139047] result >>: 15530628270
2017-05-11 16:49:15.018 CCZCheckResult[1245:139047] kkkhttp://Jwww.baiduJ.com
2017-05-11 16:49:15.018 CCZCheckResult[1245:139047] 2, kkkhttp://Jwww.baiduJ.com