LoginSignup
25
27

More than 5 years have passed since last update.

文字列からURLを抽出する方法

Last updated at Posted at 2014-11-05

簡単な正規表現を用いてURLを抽出するメモ

抽出


- (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を作成する
    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;

}

使い方

ViewController.m
- (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でした>

25
27
0

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
25
27