How do you use NSRegularExpression's replacementStringForResult:inString:offset:template:

前端 未结 6 914
清酒与你
清酒与你 2020-12-31 06:30

I have a series of characters that I want to match with a regular expression, and replace them with specific strings depending on what they are.

Example:

In

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-31 07:22

    I was looking for something similar, but didn't like most of the answers here, so I wrote something inspired by how PHP does string replacement:

    @implementation NSString (preg_replace)
    
    - (instancetype)stringByReplacingMatchesFromRegularExpression:(NSRegularExpression *)regularExpression replacementBlock:(NSString * (^)(NSArray *matches))replacementBlock
    {
        NSMutableString *finalString = self.mutableCopy;
        NSUInteger offset = 0;
    
        for (NSTextCheckingResult *match in [regularExpression matchesInString:self options:0 range:NSMakeRange(0, self.length)]) {
            NSMutableArray *matches = [NSMutableArray array];
            for (NSUInteger index = 0; index < match.numberOfRanges; ++index) {
                [matches addObject:[self substringWithRange:[match rangeAtIndex:index]]];
            }
            NSString *replacementString = replacementBlock(matches.copy);
    
            [finalString replaceCharactersInRange:NSMakeRange(match.range.location + offset, match.range.length) withString:replacementString];
            offset += replacementString.length - match.range.length;
        }
    
        return finalString;
    }
    
    @end
    

    To use it:

    NSRegularExpression *expression = [[NSRegularExpression alloc] initWithPattern:@"[0-9A-F]{2}" options:0 error:nil];
    NSString *string = @"AB-DE-EF";
    NSString *result = [string stringByReplacingMatchesFromRegularExpression:expression replacementBlock:^NSString *(NSArray *matches) {
        return [NSString stringWithFormat:@"(%@)", [matches[0] lowercaseString]];
    }];
    NSLog(@"Result = %@", result); // "(ab)-(de)-(ef)"
    

提交回复
热议问题