iOS中的正则运用

chenqiangdage 2019-06-21

一、NSRegularExpression

1. 正则表达式的创建

+ (nullable NSRegularExpression *)regularExpressionWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error;

- (nullable instancetype)initWithPattern:(NSString *)pattern options:(NSRegularExpressionOptions)options error:(NSError **)error

该类中的属性

  • pattern 返回正则表达式模式
  • options 返回创建正则表达式选项时使用的选项
  • numberOfCaptureGroups 返回正则表达式模式

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] 匹配到的第一组:aa
NSRegularExpressionDemo[82046:8220904] 匹配到的个数3
NSRegularExpressionDemo[82046:8220904] 匹配到的数据:aa
NSRegularExpressionDemo[82046:8220904] 匹配到的数据:aa
NSRegularExpressionDemo[82046:8220904] 匹配到的数据:aa
NSRegularExpressionDemo[82046:8220904] 匹配到第一组的位置:开始位置0--长度2
NSRegularExpressionDemo[82046:8220904] 替换后的字符串:bbbbbbcccdebbbbrgdo14141214bbbbghfh56821d3gad4
NSRegularExpressionDemo[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

四、正则表达式

正则语法

相关推荐