问题描述
帮我编写代码,如如果我的字符串是有效的URL,请执行smth
是否可以用几行代码编写这个代码?
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?
推荐答案
我将假设通过URL,您指的是标识互联网资源位置的字符串。
I will assume that by URL, you are referring to a string identifying a internet resource location.
如果您对输入字符串的格式有所了解,那么为什么不手动检查字符串是否以 http://
, https://
或您需要的任何其他方案。如果您期望其他协议,您也可以将它们添加到检查列表中(例如 ftp://
, mailto://
等等)
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 ([myString hasPrefix:@"http://"] || [myString hasPrefix:@"https://"])
{
// do something
}
如果您正在寻找更可靠的解决方案并检测任何类型的URL方案,那么您应该使用正则表达式。
If you are looking for a more solid solution and detect any kind of URL scheme, then you should use a regular expression.
作为旁注,NSURL类旨在表达任何类型的资源位置(而不仅仅是Internet资源)。这就是为什么,字符串如 img / demo.jpg
或 file://bla/bla/bla/demo.jpg
可以转换为NSURL对象。
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
or file://bla/bla/bla/demo.jpg
can be transformed into NSURL objects.
但是,根据文档, [NSURL URLWithString]
应返回nil如果输入字符串不是有效的Internet资源字符串。在实践中它没有。
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.
这篇关于如何快速检查NSString对象是否是一个有效的URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!