如何检查字符串是否包含URL

时间:2011-08-04 07:09:31

标签: iphone nsstring

我有短信,我想检查它是否包含文本“http”或其中存在的URL。

我该如何检查?

3 个答案:

答案 0 :(得分:6)

NSString *string = @"xxx http://someaddress.com";
NSString *substring = @"http:";

区分大小写的示例:

NSRange textRange = [string rangeOfString:substring];

if(textRange.location != NSNotFound){
    //Does contain the substring
}else{
    //Does not contain the substring
}

不区分大小写的示例:

NSRange textRange = [[string lowercaseString] rangeOfString:[substring lowercaseString]];

if(textRange.location != NSNotFound){
    //Does contain the substring
}else{
    //Does not contain the substring
}

答案 1 :(得分:2)

@Cyprian提供了一个很好的选择。

您还可以考虑使用NSRegularExpression,这样可以提供更大的灵活性,假设您需要的是,例如如果你想匹配http://和https://。

答案 2 :(得分:0)

网址通常包含http或https

您可以使用自定义方法containsString来检查这些字符串。

- (BOOL)containsString:(NSString *)string {
    return [self containsString:string caseSensitive:NO];
}
- (BOOL)containsString:(NSString*)string caseSensitive:(BOOL)caseSensitive {
    BOOL contains = NO;
    if (![NSString isNilOrEmpty:self] && ![NSString isNilOrEmpty:string]) {
        NSRange range;
        if (!caseSensitive) {
            range =  [self rangeOfString:string options:NSCaseInsensitiveSearch];
        } else {
            range =  [self rangeOfString:string];
        }
        contains = (range.location != NSNotFound);
    }

    return contains;
}

示例:

[yourString containsString:@"http"]

[yourString containsString:@"https"]