如何快速检查 NSString 对象是否是有效的 url?
帮我写这样的代码:“如果我的字符串是有效的 URL,请执行以下操作” 是否可以用几串代码来写这个?
Help me to write the code like "if my string is a valid URL do smth"
Is it possible to write this in a couple strings of code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我假设通过 URL,您指的是标识互联网资源位置的字符串。
如果您对输入字符串的格式有所了解,那么为什么不手动检查字符串是否以
http://
、https://
或任何其他方案开头你需要。 其他协议,您也可以将它们添加到检查列表中(例如ftp://
、mailto://
等)。如果您需要 可靠的解决方案并检测任何类型的 URL 方案,那么您应该使用正则表达式。
附带说明一下,NSURL 类旨在表达任何类型的资源位置(不仅仅是互联网资源)。这就是为什么像
img/demo.jpg
或file://bla/bla/bla/demo.jpg
这样的字符串可以转换为 NSURL 对象。但是,根据文档,如果输入字符串不是有效的互联网资源字符串,则
[NSURL URLWithString]
应返回 nil。但实际上并非如此。I will assume that by URL, you are referring to a string identifying a internet resource location.
If you have an idea about the format of the input string , then why not manually check if the string starts with
http://
,https://
or any other scheme you need. If you expect other protocols, you can also add them to the check list (e.g.ftp://
,mailto://
, etc)If you are looking for a more solid solution and detect any kind of URL scheme, then you should use a regular expression.
As a side note, the NSURL class is designed to express any kind of resource location (not just internet resources). That is why, strings like
img/demo.jpg
orfile://bla/bla/bla/demo.jpg
can be transformed into NSURL objects.However, according to the documentation the
[NSURL URLWithString]
should return nil if the input string is not a valid internet resource string. In practice it doesn't.我使用了这个解决方案,这显然是比正则表达式检查更好且更简单的检查 -
I used this solution which is apparently a better and less complex check than a Regex check -
尝试用它创建 NSUrl,并查看它是否返回非零结果。
Try to create NSUrl with it, and see if it returns non-nil result.