Evgeniy Kleban
Evgeniy Kleban

Reputation: 6940

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".

I have 3 predefined social host strings:

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

So my question is:

1) How to check whether string contain one of this strings i pre-define

2) how to extract string followed by this strings

For example, i get "https://www.instagram.com/myUserId12345", and i want to get myUserId12345

Upvotes: 2

Views: 1547

Answers (6)

PruitIgoe
PruitIgoe

Reputation: 6384

Since you are trying to parse URLs why reinvent the wheel when Apple has already done the heavy lifting for you with 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])

Upvotes: 0

vadian
vadian

Reputation: 285064

These strings are URL representations. Create an URL and compare the host and get the 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.

Upvotes: 5

cwwise
cwwise

Reputation: 101

  1. You can use hasPrefix or contains to do. but I think hasPrefix may be best.

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

  2. can use URL or separated String

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

Upvotes: 1

Vlad Khambir
Vlad Khambir

Reputation: 4383

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)

Upvotes: 1

axelspark
axelspark

Reputation: 198

You can use the built in RegEx in Swift:

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

Upvotes: 1

nerowolfe
nerowolfe

Reputation: 4817

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)

Upvotes: 0

Related Questions