抽出
- (NSArray *)pickUpURLFromString:(NSString *)string {
NSError *error = nil;
NSString *URLPattern = @"(http://|https://){1}[\\w\\.\\-/:]+";
NSRegularExpression *regularExpressionForPickOut = [NSRegularExpression regularExpressionWithPattern:URLPattern options:0 error:&error];
NSArray *matchesInString = [regularExpressionForPickOut matchesInString:string options:0 range:NSMakeRange(0, string.length)];
NSMutableArray *strings = [NSMutableArray array];
for (int i=0 ; i<matchesInString.count ; i++) {
NSTextCheckingResult *checkingResult = matchesInString[i];
NSString *expressionPattern = [string substringWithRange:[checkingResult rangeAtIndex:0]];
[strings addObject:expressionPattern];
}
return strings;
}
置換
- (NSString *)replaceString:(NSString *)string fromURLs:(NSArray *)urls toTemplate:(NSString *)template{
NSError *error;
NSString *expressionPattern = [urls componentsJoinedByString:@"|"];
NSRegularExpression *regularExpressionForReplace = [NSRegularExpression regularExpressionWithPattern:expressionPattern options:0 error:&error];
NSString *replacedString = [regularExpressionForReplace stringByReplacingMatchesInString:string options:0 range:NSMakeRange(0,string.length) withTemplate:template];
return replacedString;
}
使い方
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *string = @"http://qiita.com/ と http://www.google.com";
NSArray *urls = [self pickUpURLFromString:string];
NSString *replacedText = [self replaceString:string fromURLs:urls toTemplate:@"<ここURLでした>"];
NSLog(@"before : %@",string);
NSLog(@"hit urls : %@",urls);
NSLog(@"after : %@",replacedText);
}
結果
before : http://qiita.com/ と http://www.google.com
hit urls : (
"http://qiita.com/",
"http://www.google.com"
)
after : <ここURLでした> と <ここURLでした>