Swift - 如何从给定的字符串中获取特定的子字符串

时间:2017-09-05 08:01:21

标签: swift

我有字符串,由一个预定义的字符串+随机字母组成, 比如“https://www.facebook.com/”和“userId”。

我有3个预定义的社交主机字符串:

let vkPredefinedHost = "https://vk.com/"
let fbPredefinedHost = "https://www.facebook.com/"
let instPredefinedHost = "https://www.instagram.com/"

我想要的是,提取社交ID,这是一个字符串后面跟着那个字符串(我不知道到底是哪一个)。

所以我的问题是:

1)如何检查字符串是否包含我预先定义的字符串之一

2)如何提取字符串后跟此字符串

例如,我得到“https://www.instagram.com/myUserId12345”,我想获得myUserId12345

6 个答案:

答案 0 :(得分:5)

这些字符串是URL表示。创建URL并比较 host ,然后获取 path
例如

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)
}

必须从路径中删除第一个字符(前导斜杠)。

你甚至可以写

let userID = url.lastPathComponent

如果有更多的路径组件,并且所请求的信息是最后一个。

答案 1 :(得分:1)

试试此扩展程序:

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)

答案 2 :(得分:1)

您可以在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

答案 3 :(得分:1)

  1. 您可以使用hasPrefixcontains来执行此操作。 但我认为hasPrefix可能是最好的。

    let instPredefinedHost = "https://www.instagram.com/" let userUrlString = "https://www.instagram.com/myUserId12345" let result = userUrlString.hasPrefix(instPredefinedHost) let result = userUrlString.contains(instPredefinedHost)

  2. 可以使用URL或分隔的字符串

    let instPredefinedHost = "https://www.instagram.com/" let userUrl = URL(string: userUrlString) let socialId = userUrl?.lastPathComponent let socialId = userUrlString.components(separatedBy: instPredefinedHost).last

答案 4 :(得分:0)

您可以使用此类扩展程序:

var nightclubs = []
$.each(v.info, function(index, entry{ 
nightclubs.push(entry.info.nightclub);
}
console.log(nightclubs)

简单地使用

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)
    }
}

}

答案 5 :(得分:0)

既然您正在尝试解析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)")
} 

打印:

Optional("https")
Optional("www.instagram.com")
/myUserId12345
Optional([test=testvar, test2=teststatic])
相关问题