Friday, June 15, 2012

NSRegularExpression で正規表現マッチ&置換

iOS3.2 から NSString の rangeOfString:options:(NSStringCompareOptions) に NSRegularExpressionSearch が追加されて正規表現が使えます。

NSString *str = @"Example URL: http://example.net ...";
NSString *pattern = @"(https?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)";
NSRange match = [
    str rangeOfString:pattern
    options:NSRegularExpressionSearch
];
if (match.location != NSNotFound) {
    NSLog(@"%@", [str substringWithRange:match]);
}

置換は iOS4.0 / OS X v10.7 以降であれば、NSRegularExpression が使えます。

NSString *source = @"Example URL: http://example.net ...";
NSString *pattern = @"(https?://[-_.!~*'()a-zA-Z0-9;/?:@&=+$,%#]+)";
NSString *replacement = @"$1";

NSRegularExpression *regexp = [NSRegularExpression
    regularExpressionWithPattern:pattern
    options:NSRegularExpressionCaseInsensitive
    error:nil
];

NSString *str = [regexp
    stringByReplacingMatchesInString:source
    options:NSMatchingReportProgress
    range:NSMakeRange(0, source.length)
    withTemplate:replacement
];
NSLog(@"%@",  str);