xcode 检查字符串是否为 url - Objective-C
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7016957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking if a string is a url - Objective-C
提问by CodeGuy
Possible Duplicate:
How to validate an url on the iPhone
可能重复:
如何在 iPhone 上验证 url
In Objective-C, does anyone have a good method to test if a given string appears to be a URL?
在 Objective-C 中,有没有人有一个很好的方法来测试给定的字符串是否看起来是一个 URL?
采纳答案by mattacular
You can use a regular expression. For iPhone 3 and up, you can do it without a framework. Otherwise use RegexKitLite or something.
您可以使用正则表达式。对于 iPhone 3 及更高版本,您无需框架即可完成。否则使用 RegexKitLite 或其他东西。
Here is a regex pattern for checking URLs:
这是用于检查 URL 的正则表达式模式:
"(http|https)://((\w)*|([0-9]*)|([-|_])*)+([\.|/]((\w)*|([0-9]*)|([-|_])*))+"
Doing it without a framework:
在没有框架的情况下进行:
- (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];
}
回答by PeyloW
Do this:
做这个:
NSURL* url = [NSURL URLWithString:stringToTest];
if (url && url.scheme && url.host)//This comparision never fails
{
//the url is ok
NSLog(@"%@ is a valid URL", yourUrlString);
}
If stringToTest
is indeed an URL then url will be instantiate as expected. Otherwise +[NSURL URLWithString:]
return nil
.
如果stringToTest
确实是一个 URL,那么 url 将按预期实例化。否则+[NSURL URLWithString:]
返回nil
。
Most methods in Cocoa Touch return nil
on illegal input, very few actually throws an NSInvalidArgumentException
. Each method is documented with what they return on invalid input.
Cocoa Touch 中的大多数方法都会返回nil
非法输入,很少会真正抛出NSInvalidArgumentException
. 每个方法都记录了它们在无效输入时返回的内容。