2

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

3

6 Answers 6

5

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.

Sign up to request clarification or add additional context in comments.

5 Comments

This is better approach
Also you can use URLComponents. *Well it won't help with finding stuff in path tho.
@user28434 Yes, but you can take advantage only if query is involved.
@vadian thanks, it work in that specific case but i would prefer universal extension that we can apply for cases in which string is not url :)
A more universal solution is regular expression (regex) but you need to specify the range / boundaries of the substring to be extracted anyway.
1

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

Comments

1

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)

Comments

1
  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

Comments

0

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)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.