iOS 正则表达式

1. iOS中使用正则表达式,用 NSRegularExpression 这个类

实例化方法:

NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:@"在引号内写正则表达式" options:NSRegularExpressionCaseInsensitive error:nil];

NSRegularExpressionCaseInsensitive 是指大小写敏感

1.1 使用正则表达式校验手机号

示例代码:

 1         // 假设手机号只以131518开头
 2         NSString *str = @"13510188591";
 3         
 4         // 实例化正则表达式对象
 5         NSRegularExpression *regex = [[NSRegularExpression alloc]initWithPattern:@"1[358][0-9]{9}" options:NSRegularExpressionCaseInsensitive error:nil];
 6         // 匹配
 7         NSArray *matches = [regex matchesInString:str options:NSMatchingReportCompletion range:NSMakeRange(0, str.length)];
 8         
 9         // 判断,
10         if (matches.count) {
11             NSLog(@"匹配到了");
12             // 正则表达式对位数不做精确控制,假如提供100位的数字,上面的代码还是会认为匹配到了,所以需要用下面代码完善手机号匹配
13             if (str.length == 11) {
14                 NSLog(@"并且是手机号!");
15             }
16             
17         }else{
18             NSLog(@"没匹配到");
19         }

1.2 其他常用方法

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

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

2.好用的第3方框架 RegexKitLite

该库依赖于 libicucore.dylib.

如果是ARC项目,还得加上 -fno-objc-arc

示例代码:

1         // 假设手机号只以131518开头
2         NSString *str = @"135101885910000";
3         NSString *regex = @"1[358][0-9]{9}";
4         [str enumerateStringsMatchedByRegex:regex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
5             NSLog(@"匹配到的数量:%ld",captureCount);
6             NSLog(@"匹配到的字符串:%@",*capturedStrings);
7             NSLog(@"匹配到的Range:%@",NSStringFromRange(*capturedRanges));
8             
9         }];

另一种常见用法,打印 分割字符串

1         // 假设手机号只以131518开头
2         NSString *str = @"13512345678ABCD18912345678-15812345678";
3         NSString *regex = @"1[358][0-9]{9}";
4 
5         [str enumerateStringsSeparatedByRegex:regex usingBlock:^(NSInteger captureCount, NSString *const __unsafe_unretained *capturedStrings, const NSRange *capturedRanges, volatile BOOL *const stop) {
6                        NSLog(@"匹配到的数量:%ld",captureCount);
7                        NSLog(@"匹配到的字符串:%@",*capturedStrings);
8                        NSLog(@"-----匹配到的Range:%@",NSStringFromRange(*capturedRanges));
9         }];

输出结果:

匹配到的数量:1

匹配到的字符串:

-----匹配到的Range:{0, 0}

匹配到的数量:1

匹配到的字符串:ABCD

-----匹配到的Range:{11, 4}

匹配到的数量:1

匹配到的字符串:-

-----匹配到的Range:{26, 1}

原文地址:https://www.cnblogs.com/oumygade/p/4223000.html