ios - 验证 iOS 的 url 以 www 开头

标签 ios objective-c iphone regex

我想要 url 以 www 开头并以任何类型结尾,例如 .com 、 .co 等

example - www.example.com or any other.

我试过了

-(BOOL) validateUrl: (NSString *) candidate {
NSString *urlRegEx =
@"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", urlRegEx]; 
return [urlTest evaluateWithObject:candidate];
}

但它适用于 http 和 https

最佳答案

正则表达式非常强大,但是对于这个简单的例子,两个类别方法怎么样。

@implementation NSString (SuffixTest)

- (BOOL)jc_startsWithAnyOf:(NSArray*)prefixes
{
    for (NSString *candidate in prefixes) {
        if ([self hasPrefix:candidate]) {
            return YES;
        }
    }
    return NO;
}

- (BOOL)jc_endsWithAnyOf:(NSArray *)suffixes
{
    for (NSString *candidate in suffixes) {
        if ([self hasSuffix:candidate]) {
            return YES;
        }
    }
    return NO;
}


@end

然后使用为:

- (BOOL)isValidAddress:(NSString*)string
{
    return [string jc_startsWithAnyOf:@[@"http://www.", @"https://www."]] && 
        [string jc_endsWithAnyOf:@[@"com", @"org"]];
}

。 。 。稍微详细一点,但至少不需要查阅正则表达式文档来理解代码。

关于ios - 验证 iOS 的 url 以 www 开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26886698/

相关文章:

ios - 如何快速创建过滤器数组

android - 使用免费 IOS 应用程序的 SaaS 模型的订阅计费

html - iOS WebView控件的HTML中的音频不起作用

ios - 应用程序 :didReceiveLocalNotification: not called when app in background

iphone - 如何在iOS模拟器上查看通知中心?

javascript - 我如何知道某个应用程序是否已通过 Safari 安装在 iPhone 上

ios - 在不覆盖 iPhone 上的当前 View 的情况下呈现模态视图 Controller

ios - Core Plot 中的 expandRangeByFactor 方法出错

objective-c - cocoa 绘图可点击文本

iphone - 我应该在每个 View 中都有一个 NSFetchedResultsController 吗?