首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NSRegularExpression验证URL

NSRegularExpression验证URL
EN

Stack Overflow用户
提问于 2011-01-19 17:26:34
回答 2查看 6.3K关注 0票数 5

我在一个网站上找到了这个正则表达式。据说这是最好的URL验证表达式,我同意。迭戈·佩里尼创造的。

当我试图与objective-C一起使用它来检测字符串上的URL时,我面临的问题是。我尝试过使用NSRegularExpressionAnchorsMatchLinesNSRegularExpressionIgnoreMetacharacters等选项,但仍然没有成功。

表达式是否为Objective-C格式化得不好?我是不是遗漏了什么?有什么想法吗?

我也尝试过John的regex,但是它在一些无效的URL中失败了。

代码语言:javascript
复制
        Regular Expression                                  Explanation of expression                      

 ^                                                  match at the beginning
//Protocol identifier
(?:
    (?:https?|ftp                                   http, https or ftp
    ):\\/\\/                                        ://
)?                                                  optional
// User:Pass authentication
(?:
    ^\\s+                                           non white spaces, 1 or more times
    (?:
        :^\\s*                                      : non white spaces, 0 or more times, optionally
    )?@                                             @
)?                                                  optional
//Private IP Addresses                              ?! Means DO NOT MATCH ahead. So do not match any of the following
(?:
    (?!10                                           10                                                          10.0.0.0 - 10.999.999.999
        (?:
            \\.\\d{1,3}                             . 1 to 3 digits, three times
        ){3}
    )
    (?!127                                          127                                                         127.0.0.0 - 127.999.999.999
        (?:
            \\.\\d{1,3}                             . 1 to 3 digits, three times
        ){3}
    )
    (?!169\\.254                                    169.254                                                     169.254.0.0 - 169.254.999.999
        (?:
            \\.\\d{1,3}                             . 1 to 3 digits, two times
        ){2}
    )
    (?!192\\.168                                    192.168                                                     192.168.0.0 - 192.168.999.999
        (?:
            \\.\\d{1,3}                             . 1 to 3 digits, two times
        ){2}
    )
    (?!172\\.                                       172.                                                        172.16.0.0 - 172.31.999.999
        (?:                                                                                                             
            1[6-9]                                  1 followed by any number between 6 and 9
            |                                       or
            2\\d                                    2 and any digit
            |                                       or
            3[0-1]                                  3 followed by a 0 or 1
        )
        (?:
            \\.\\d{1,3}                             . 1 to 3 digits, two times
        ){2}
    )
    //First Octet IPv4                              // match these. Any non network or broadcast IPv4 address
    (?:
        [1-9]\\d?                                   any number from 1 to 9 followed by an optional digit        1 - 99
        |                                           or
        1\\d\\d                                     1 followed by any two digits                                100 - 199
        |                                           or
        2[01]\\d                                    2 followed by any 0 or 1, followed by a digit               200 - 219
        |                                           or
        22[0-3]                                     22 followed by any number between 0 and 3                   220 - 223
    )
    //Second and Third Octet IPv4
    (?:
        \\.                                         .
        (?:
            1?\\d{1,2}                              optional 1 followed by any 1 or two digits                  0 - 199
            |                                       or
            2[0-4]\\d                               2 followed by any number between 0 and 4, and any digit     200 - 249
            |                                       or
            25[0-5]                                 25 followed by any numbers between 0 and 5                  250 - 255
        )
    ){2}                                            two times
    //Fourth Octet IPv4
    (?:
        \\.                                         .
        (?:
            [1-9]\\d?                               any number between 1 and 9 followed by an optional digit    1 - 99
            |                                       or
            1\\d\\d                                 1 followed by any two digits                                100 - 199
            |                                       or
            2[0-4]\\d                               2 followed by any number between 0 and 4, and any digit     200 - 249
            |                                       or
            25[0-4]                                 25 followed by any number between 0 and 4                   250 - 254
        )
    )
    //Host name
    |                                               or                  
    (?:
        (?:
            [a-z\u00a1-\uffff0-9]+-?                any letter, digit or character one or more times with optional -
        )*                                          zero or more times
        [a-z\u00a1-\uffff0-9]+                      any letter, digit or character one or more times
    )
    //Domain name
    (?:
        \\.                                         .
        (?:
            [a-z\u00a1-\uffff0-9]+-?                any letter, digit or character one or more times with optional -
        )*                                          zero or more times
        [a-z\u00a1-\uffff0-9]+                      any letter, digit or character one or more times
    )*                                              zero or more times
    //TLD identifier
    (?:
        \\.                                         .
        (?:
            [a-z\u00a1-\uffff]{2,}                  any letter, digit or character more than two times
        )
    )
)
//Port number
(?:
    :\\d{2,5}                                       : followed by any digit, two to five times, optionally
)?              
//Resource path
(?:
    \\/[^\\s]*                                      / followed by an optional non space character, zero or more times
)?                                                  optional
$                                                  match at the end

编辑--我想我忘记在下面的代码中使用这个表达式了:(部分代码)

代码语言:javascript
复制
NSError *error = NULL;
NSRegularExpression *detector = [NSRegularExpression regularExpressionWithPattern:[self theRegularExpression] options:0 error:&error];
NSArray *links = [detector matchesInString:theText options:0 range:NSMakeRange(0, theText.length)];
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-01-20 16:00:35

代码语言:javascript
复制
^(?i)(?:(?:https?|ftp):\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?$

是我找到的最佳URL验证正则表达式,并在我的问题上进行了解释。它已经被格式化为工作目标-C。然而,与NSRegularExpression一起使用它给我带来了各种各样的问题,包括我的应用程序崩溃。RegexKitLite处理它没有任何问题。我不知道这是一个大小限制或一些标志没有被设置。我的最后代码看起来是:

代码语言:javascript
复制
//First I take the string and put every word in an array, then I match every word with the regular expression
NSArray *splitIntoWordsArray = [textToMatch componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewLineCharacterSet]];
NSMutableString *htmlString = [NSMutableString stringWithString:textToMatch];
for (NSString *theText in splitIntoWordsArray){
    NSEnumerator *matchEnumerator = [theText matchEnumeratorWithRegex:theRegularExpressionString];
    for (NSString *temp in matchEnumerator){
        [htmlString replaceOccurrencesOfString:temp withString:[NSString stringWithFormat:@"<a href=\"%@\">%@</a>", temp, temp] options:NSLiteralSearch range:NSMakeRange(0, [htmlString length])];
    }
}
[htmlString replaceOccurrencesOfString:@"\n" withString:@"<br />" options:NSLiteralSearch range:NSMakeRange(0, htmlString.length)];
//embed the text on a webView as HTML
[webView loadHTMLString:[NSString stringWithFormat:embedHTML, [mainFont fontName], [mainFont pointSize], htmlString] baseURL:nil];

其结果是:一个带有嵌入HTML的UIWebView,其中URL和电子邮件是可点击的。不要忘记设置dataDetectorTypes = UIDataDetectorTypeNone

你也可以试试

代码语言:javascript
复制
NSError *error = NULL;
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"(?i)(?:(?:https?):\\/\\/)?(?:\\S+(?::\\S*)?@)?(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))(?::\\d{2,5})?(?:\\/[^\\s]*)?" options:NSRegularExpressionCaseInsensitive error:&error];
if (error)
    NSLog(@"error");
NSString *someString = @"This is a sample of a sentence with a URL http://. http://.. http://../ http://? http://?? http://??/ http://# http://-error-.invalid/ http://-.~_!$&'()*+,;=:%40:80%2f::::::@example.com within it.";
NSRange range = [expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])];
if (!NSEqualRanges(range, NSMakeRange(NSNotFound, 0))){
    NSString *match = [someString substringWithRange:range];
    NSLog(@"%@", match);
}   
else {
    NSLog(@"no match");
}

希望它能对未来的人有所帮助

正则表达式有时会导致应用程序挂起,所以我决定使用gruber的正则表达式来识别没有协议或www部分的url:

代码语言:javascript
复制
(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/?)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))*(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’])*)
票数 9
EN

Stack Overflow用户

发布于 2011-01-19 18:12:50

,我是不是遗漏了什么?

你错过了为你做这件事的内置东西。有一个名为NSDataDetector的方便的对象。创建它是为了查找特定的数据“类型”(比如,NSTextCheckingTypeLink),然后向它请求它的-matchesInString:options:range:

Here's an earlier answer of mine showing how to use it

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4738521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档