2
2

More than 5 years have passed since last update.

先頭の大文字小文字を維持して文字列置換する方法

Last updated at Posted at 2014-08-23

NSRegularExpressionを用いると文字列の検索、置換が容易にできます。しかし、以下のように置換される文字列の先頭の大文字小文字の別を維持したまま置換することは正規表現だけでは難しいです。

hogeをpoiに置換
hoge -> poi
Hoge -> Poi

この処理を拙作Arrow Noteに実装したので、コードを公開します。

Objective-C
-(NSString*) replaceString:(NSString*)search with:(NSString*)replace in:(NSString*)text
{
    NSRegularExpression *regex
     = [NSRegularExpression regularExpressionWithPattern:search
                            options:NSRegularExpressionCaseInsensitive
                            error:nil];
    NSMutableString *target = [[NSMutableString alloc]
                               initWithString:text];
    NSTextCheckingResult *r = [regex firstMatchInString:target
                                     options:0
                                     range:NSMakeRange(0, target.length)];
    while (nil != r && NSNotFound != r.range.location) {
        NSString *src = [target substringWithRange:r.range];
        NSString *rep = [regex replacementStringForResult:r
                               inString:target
                               offset:0
                               template:replace];
        if (0 < src.length && 0 < rep.length
            && isupper([src characterAtIndex:0])) {
            rep = [[NSString alloc] initWithFormat:@"%c%@",
                                    toupper([rep characterAtIndex:0]),
                                    [rep substringFromIndex:1]];
        }
        [target replaceCharactersInRange:r.range withString:rep];
        NSUInteger nextPos = r.range.location + rep.length;
        r = [regex firstMatchInString:target
                   options:0
                   range:NSMakeRange(nextPos, target.length - nextPos)];
    }
    return target;
}

2
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2