[英]Swift - how to get specific substring from a given string
I have string, that consist of one pre-defined string + random letters, like " https://www.facebook.com/ " and "userId". 我有字符串,由一个预定义的字符串+随机字母组成,如“ https://www.facebook.com/ ”和“userId”。
I have 3 predefined social host strings: 我有3个预定义的社交主机字符串:
let vkPredefinedHost = "https://vk.com/"
let fbPredefinedHost = "https://www.facebook.com/"
let instPredefinedHost = "https://www.instagram.com/"
What i want is, extract social id, which is a string followed by that string (i don't know exactly which one i get). 我想要的是,提取社交ID,这是一个字符串后面跟着那个字符串(我不确切知道我得到了哪一个)。
So my question is: 所以我的问题是:
1) How to check whether string contain one of this strings i pre-define 1)如何检查字符串是否包含我预先定义的字符串之一
2) how to extract string followed by this strings 2)如何提取字符串后跟此字符串
For example, i get " https://www.instagram.com/myUserId12345 ", and i want to get myUserId12345 例如,我得到“ https://www.instagram.com/myUserId12345 ”,我想得到myUserId12345
These strings are URL representations. 这些字符串是URL表示。 Create an
URL
and compare the host
and get the path
创建一个
URL
并比较host
并获取path
for example 例如
let host = "www.instagram.com"
if let url = URL(string: "https://www.instagram.com/myUserId12345"),
url.host == host {
let userID = String(url.path.characters.dropFirst())
print(userID)
}
It's necessary to drop the first character (a leading slash) from the path. 必须从路径中删除第一个字符(前导斜杠)。
You can even write 你甚至可以写
let userID = url.lastPathComponent
if there are more path components and the requested information is the last one. 如果有更多的路径组件,并且所请求的信息是最后一个。
Try this extension: 试试这个扩展:
let instPredefinedHost = "https://www.instagram.com/"
let text = "https://www.instagram.com/myUserId12345"
extension String {
func getNeededText(for host: String) -> String {
guard range(of: host) != nil else { return "" }
return replacingOccurrences(of: host, with: "")
}
}
text.getNeededText(for: instPredefinedHost)
You can use the built in RegEx in Swift: 您可以在Swift中使用内置的RegEx:
let hostString = "Put your string here"
let pattern = "https:\/\/\w+.com\/(\w)" // any https://___.com/ prefix
let regex = try! NSRegularExpression(pattern: pat, options: [])
let match = regex.matchesInString(hostString, options: [], range: NSRange(location: 0, length: hostString.characters.count))
print(match[0]) // your social id
You can use hasPrefix
or contains
to do. 您可以使用
hasPrefix
或contains
来执行。 but I think hasPrefix
may be best. 但我认为
hasPrefix
可能是最好的。
let instPredefinedHost = "https://www.instagram.com/" let userUrlString = "https://www.instagram.com/myUserId12345" let result = userUrlString.hasPrefix(instPredefinedHost) let result = userUrlString.contains(instPredefinedHost)
can use URL or separated String 可以使用URL或分隔的String
let instPredefinedHost = "https://www.instagram.com/" let userUrl = URL(string: userUrlString) let socialId = userUrl?.lastPathComponent let socialId = userUrlString.components(separatedBy: instPredefinedHost).last
You can use such type of extension: 您可以使用此类扩展名:
extension String{
func exclude(_ find:String) -> String {
return replacingOccurrences(of: find, with: "", options: .caseInsensitive, range: nil)
}
func replaceAll(_ find:String, with:String) -> String {
return replacingOccurrences(of: find, with: with, options: .caseInsensitive, range: nil)
}
}
}
And use simply 简单地使用
let myaccount = fullString.exclude(find : instPredefinedHost)
Since you are trying to parse URLs why reinvent the wheel when Apple has already done the heavy lifting for you with URLComponents? 既然您正在尝试解析URL,那么当Apple已经使用URLComponents为您完成了繁重的工作时,为什么要重新发明轮子?
let myURLComps = URLComponents(string: "https://www.instagram.com/myUserId12345?test=testvar&test2=teststatic")
if let theseComps = myURLComps {
let thisHost = theseComps.host
let thisScheme = theseComps.scheme
let thisPath = theseComps.path
let thisParams = theseComps.queryItems
print("\(thisScheme)\n\(thisHost)\n\(thisPath)\n\(thisParams)")
}
prints: 打印:
Optional("https")
Optional("www.instagram.com")
/myUserId12345
Optional([test=testvar, test2=teststatic])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.