我有一个包含许多路径组件的网址。是否有一种优雅的方法来删除所有路径组件?基本上,我只想保留该方案和URL的主机。和端口,如果可用。
我当然可以使用现有网址中的相关属性创建新的网址对象:
let newURL = "\(existingURL.scheme!)://\(existingURL.host!)"
或者遍历路径组件,删除最后一个组件,直到没有。
但这两种解决方案看起来都不那么优雅,所以我正在寻找一种更好,更安全,更有效的解决方案。
答案 0 :(得分:2)
我看到的唯一可能是使用URLComponents
并手动删除一些组件:
let url = URL(string: "http://www.google.com/and/my/path")!
print(url)
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
components.path = ""
print(components.url!) // http://www.google.com
如果您决定手动构建网址,那么使用URLComponents
可能更好:
let url = URL(string: "http://www.google.com/and/my/path")!
var components = URLComponents()
components.scheme = url.scheme
components.host = url.host
print(components.url!)
答案 1 :(得分:0)
您可以尝试使用Regex方法。它会比其他方式更优雅。我刚做了快速代码。正则表达式可能无法正常工作,但您将获得更多针对您的查询类型的正则表达式示例。
let urlRegEx = "((http(s)?:\\(/)\\/)|(\\/.*){1}"
let string = "https://pixabay.com/en/art-beauty-fairytales-fantasy-2436545/"
let matched = matches(for: urlRegEx, in: string)
print(matched)
func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
答案 2 :(得分:0)
您可以使用reg-EX
let url = "http://www.somedomain.com/?f"
let pattern = "^(http://|https://)[A-Za-z0-9.-]+(?!.*\\|\\w*$)"
let regex = try! NSRegularExpression.init(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: url, options: [], range: NSMakeRange(0, url.count))
matches.enumerated().forEach({ (_, match) in
print((url as NSString).substring(with: match.range))
})