YYKit源码探究(五) —— NSString分类之Regular Expression(四)

版本记录

版本号 时间
V1.0 2018.03.20

前言

iOS圈内有几个人大家基本都知道,比如说王巍、唐巧,还有YYKit框架的作者现任职于滴滴的郭曜源 - ibireme等。这里有一篇唐巧对他的专访,还有他的 GitHub - Yaoyuan博客,这里贴出来框架YYKit 框架。接下来几篇我们就一起来看一下这个框架。感兴趣的可以看上面写的几篇。
1. YYKit源码探究(一) —— 基本概览
2. YYKit源码探究(二) —— NSString分类之Hash(一)
3. YYKit源码探究(三) —— NSString分类之Encode and decode(二)
4. YYKit源码探究(四) —— NSString分类之Drawing(三)

回顾

上一篇我们分析了NSString分类NSString+YYAddDrawing部分,这一篇我们就看一下Regular Expression部分。


API 接口

/**
 Whether it can match the regular expression
 
 @param regex  The regular expression
 @param options     The matching options to report.
 @return YES if can match the regex; otherwise, NO.
 */
- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options;

/**
 Match the regular expression, and executes a given block using each object in the matches.
 
 @param regex    The regular expression
 @param options  The matching options to report.
 @param block    The block to apply to elements in the array of matches.
 The block takes four arguments:
     match: The match substring.
     matchRange: The matching options.
     stop: A reference to a Boolean value. The block can set the value
         to YES to stop further processing of the array. The stop
         argument is an out-only argument. You should only ever set
         this Boolean to YES within the Block.
 */
- (void)enumerateRegexMatches:(NSString *)regex
                      options:(NSRegularExpressionOptions)options
                   usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block;

/**
 Returns a new string containing matching regular expressions replaced with the template string.
 
 @param regex       The regular expression
 @param options     The matching options to report.
 @param replacement The substitution template used when replacing matching instances.
 
 @return A string with matching regular expressions replaced by the template string.
 */
- (NSString *)stringByReplacingRegex:(NSString *)regex
                             options:(NSRegularExpressionOptions)options
                          withString:(NSString *)replacement;

下面我们就详细的看一下这个接口API

1. - (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options;

该方法的作用是根据固定的匹配的表达式,判断给定的字符串和调用者是否匹配。

示例调用

下面我们看一下方法的示例调用。

NSString *str = @"A";
BOOL isMatch = [str matchesRegex:@"B" options:NSRegularExpressionCaseInsensitive];
NSLog(@"是否匹配 = %d", isMatch);

看一下输出结果

2018-03-19 10:52:41.174585+0800 JJWebImage[29106:4108904] 是否匹配 = 0

再看另外一个例子

NSString *str = @"A";
BOOL isMatch = [str matchesRegex:@"a" options:NSRegularExpressionCaseInsensitive];
NSLog(@"是否匹配 = %d", isMatch);

下面看输出结果

2018-03-19 11:00:17.839901+0800 JJWebImage[29115:4111852] 是否匹配 = 1

上面这个例子就是NSRegularExpressionCaseInsensitive,也就是不区分大小写的比较。

方法实现

下面我们就看一下方法实现

- (BOOL)matchesRegex:(NSString *)regex options:(NSRegularExpressionOptions)options {
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:NULL];
    if (!pattern) return NO;
    return ([pattern numberOfMatchesInString:self options:0 range:NSMakeRange(0, self.length)] > 0);
}

2. - (void)enumerateRegexMatches:(NSString *)regex options:(NSRegularExpressionOptions)options usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block;

示例调用

下面我们看一下方法的示例调用。

NSString *str = @"A";
[str enumerateRegexMatches:@"a" options:NSRegularExpressionCaseInsensitive usingBlock:^(NSString * _Nonnull match, NSRange matchRange, BOOL * _Nonnull stop) {
    NSLog(@"匹配的字符串 = %@", match);
    NSLog(@"匹配的字符串区域 = %ld - %ld", matchRange.location, matchRange.length);
    if (matchRange.length > 0) {
        *stop = YES;
        NSLog(@"匹配的字符串匹配是否停止 = %d", *stop);
    }
}];

下面看一下输出结果

2018-03-19 11:20:48.088380+0800 JJWebImage[29143:4119629] 匹配的字符串 = A
2018-03-19 11:20:48.088562+0800 JJWebImage[29143:4119629] 匹配的字符串区域 = 0 - 1
2018-03-19 11:20:48.088602+0800 JJWebImage[29143:4119629] 匹配的字符串匹配是否停止 = 1

方法实现

下面我们就看一下方法实现。

- (void)enumerateRegexMatches:(NSString *)regex
                      options:(NSRegularExpressionOptions)options
                   usingBlock:(void (^)(NSString *match, NSRange matchRange, BOOL *stop))block {
    if (regex.length == 0 || !block) return;
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
    if (!regex) return;
    [pattern enumerateMatchesInString:self options:kNilOptions range:NSMakeRange(0, self.length) usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
        block([self substringWithRange:result.range], result.range, stop);
    }];
}

3. - (NSString *)stringByReplacingRegex:(NSString *)regex options:(NSRegularExpressionOptions)options withString:(NSString *)replacement;

返回一个新的字符串,其中包含用模板字符串替换的正则表达式。

示例调用

下面我们看一下方法的示例调用。

NSString *resultStr = [@"Assswsda" stringByReplacingRegex:@"A" options:NSRegularExpressionCaseInsensitive withString:@"h"];
NSLog(@"替换后的字符串 = %@", resultStr);

下面看一下输出结果

2018-03-19 11:47:06.570492+0800 JJWebImage[29153:4126527] 替换后的字符串 = hssswsdh

方法实现

下面我们就看一下方法实现。

- (NSString *)stringByReplacingRegex:(NSString *)regex
                             options:(NSRegularExpressionOptions)options
                          withString:(NSString *)replacement; {
    NSRegularExpression *pattern = [NSRegularExpression regularExpressionWithPattern:regex options:options error:nil];
    if (!pattern) return self;
    return [pattern stringByReplacingMatchesInString:self options:0 range:NSMakeRange(0, [self length]) withTemplate:replacement];
}

上面几个方法都有一个枚举值,就是NSRegularExpressionOptions,下面我们就看一下这个枚举值。

typedef NS_OPTIONS(NSUInteger, NSRegularExpressionOptions) {
   NSRegularExpressionCaseInsensitive             = 1 << 0,     /* Match letters in the pattern independent of case. */
   NSRegularExpressionAllowCommentsAndWhitespace  = 1 << 1,     /* Ignore whitespace and #-prefixed comments in the pattern. */
   NSRegularExpressionIgnoreMetacharacters        = 1 << 2,     /* Treat the entire pattern as a literal string. */
   NSRegularExpressionDotMatchesLineSeparators    = 1 << 3,     /* Allow . to match any character, including line separators. */
   NSRegularExpressionAnchorsMatchLines           = 1 << 4,     /* Allow ^ and $ to match the start and end of lines. */
   NSRegularExpressionUseUnixLineSeparators       = 1 << 5,     /* Treat only \n as a line separator (otherwise, all standard line separators are used). */
   NSRegularExpressionUseUnicodeWordBoundaries    = 1 << 6      /* Use Unicode TR#29 to specify word boundaries (otherwise, traditional regular expression word boundaries are used). */
};

后记

本篇我们分析了Regular Expression部分的功能,主要就是匹配的判断以及文本的替换,喜欢的给个赞~~~

推荐阅读更多精彩内容