验证没有方案的 URL [英] Validate URL without scheme
问题描述
Swift 5、Xcode 10、iOS 12
我的代码使用 UIApplication.shared.canOpenURL
来验证 URL,不幸的是,如果没有例如http://".
示例:
print(UIApplication.shared.canOpenURL(URL(string: "stackoverflow.com")!))//false打印(UIApplication.shared.canOpenURL(URL(字符串:http://stackoverflow.com")!))//true打印(UIApplication.shared.canOpenURL(URL(字符串:129.0.0.1")!))//假打印(UIApplication.shared.canOpenURL(URL(string: "ftp://129.0.0.1")!))//true
我知道 schemes (iOS9+) 并且我知道如果字符串尚未以http://"开头,我可以添加前缀,然后检查这个新字符串,但我仍然想知道:
问题:如何添加没有方案"方案,以便像stackoverflow.com"这样的有效 URL 也返回 true
(这是否可能?)?
不可能给 URL
添加一个有效的方案,因为没有人知道哪个前缀会添加到哪个 URL代码>.您可以在
regex
的帮助下验证 URL
.
我搜索并修改了正则表达式.
扩展字符串{func isValidUrl() ->布尔{让正则表达式 = "((http|https|ftp)://)?((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"let predicate = NSPredicate(格式: "SELF MATCHES %@", regex)return predicate.evaluate(with: self)}}
我使用以下网址对其进行了测试:
print("http://stackoverflow.com".isValidUrl())打印(stackoverflow.com".isValidUrl())打印("ftp://127.0.0.1".isValidUrl())打印(www.google.com".isValidUrl())打印(127.0.0.1".isValidUrl())打印(127".isValidUrl())打印(你好".isValidUrl())
<块引用>
输出
真真的真的真的真的错误的错误的
注意: 100% 正则表达式无法验证 email
和 url
Swift 5, Xcode 10, iOS 12
My code uses UIApplication.shared.canOpenURL
to validate URLs, which unfortunately fails without e.g. "http://".
Example:
print(UIApplication.shared.canOpenURL(URL(string: "stackoverflow.com")!)) //false
print(UIApplication.shared.canOpenURL(URL(string: "http://stackoverflow.com")!)) //true
print(UIApplication.shared.canOpenURL(URL(string: "129.0.0.1")!)) //false
print(UIApplication.shared.canOpenURL(URL(string: "ftp://129.0.0.1")!)) //true
I'm aware of the change with schemes (iOS9+) and I know that I can just add a prefix like "http://" if the String doesn't start with it already, then check this new String but I'm still wondering:
Question: How do I add a "there's no scheme" scheme, so valid URLs like "stackoverflow.com" return true
too (is this even possible?)?
It's not possible to add a valid scheme to URL
because no one knows which prefix will be add to which URL
. You can just validate a URL
with the help of regex
.
I searched and modified the regex.
extension String {
func isValidUrl() -> Bool {
let regex = "((http|https|ftp)://)?((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+"
let predicate = NSPredicate(format: "SELF MATCHES %@", regex)
return predicate.evaluate(with: self)
}
}
I tested it with below urls:
print("http://stackoverflow.com".isValidUrl())
print("stackoverflow.com".isValidUrl())
print("ftp://127.0.0.1".isValidUrl())
print("www.google.com".isValidUrl())
print("127.0.0.1".isValidUrl())
print("127".isValidUrl())
print("hello".isValidUrl())
Output
true
true
true
true
true
false
false
Note: 100% regex is not possible to validate the email
and url
这篇关于验证没有方案的 URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!