Objective-C - Finding a URL within a string

后端 未结 3 1578
半阙折子戏
半阙折子戏 2020-12-14 03:32

Given a large string, what is the best way to create an array of all valid urls which are contained within the string?

相关标签:
3条回答
  • 2020-12-14 04:19

    No need to use RegexKitLite for this, since iOS 4 Apple provide NSDataDetector (a subclass of NSRegularExpression).

    You can use it simply like this (source is your string) :

    NSDataDetector* detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
    NSArray* matches = [detector matchesInString:source options:0 range:NSMakeRange(0, [source length])];
    
    0 讨论(0)
  • 2020-12-14 04:19

    I'd use RegexKitLite for this:

    #import "RegExKitLite.h"
    
    ...
    
    NSString * urlString = @"blah blah blah http://www.google.com blah blah blah http://www.stackoverflow.com blah blah balh http://www.apple.com";
    NSArray *urls = [urlString componentsMatchedByRegex:@"http://[^\\s]*"];
    NSLog(@"urls: %@", urls);
    

    Prints:

    urls: (
        "http://www.google.com",
        "http://www.stackoverflow.com",
        "http://www.apple.com"
    )
    

    (Of course, the regex I've used there for urls is simplified, but you get the idea.)

    0 讨论(0)
  • 2020-12-14 04:24

    This is best way to extract url link.

    NSString *url_ = @"dkc://name.com:8080/123;param?id=123&pass=2#fragment";
    
    NSURL *url = [NSURL URLWithString:url_];
    
    NSLog(@"scheme: %@", [url scheme]);
    
    NSLog(@"host: %@", [url host]);
    
    NSLog(@"port: %@", [url port]);
    
    NSLog(@"path: %@", [url path]);
    
    NSLog(@"path components: %@", [url pathComponents]);
    
    NSLog(@"parameterString: %@", [url parameterString]);
    
    NSLog(@"query: %@", [url query]);
    
    NSLog(@"fragment: %@", [url fragment]);
    

    Output:

    scheme: dkc

    host: name.com

    port: 8080

    path: /12345

    path components: ( "/", 123 ) parameterString: param

    query: id=1&pass=2

    fragment: fragment

    0 讨论(0)
提交回复
热议问题