user3127109 user3127109 - 10 days ago 5
Swift Question

How to get only link from this string in swift

I want to get only link from this string. Example:

"<p><a href=\"https://www.youtube.com/watch?v=i2yscjyIBsk\">https://www.youtube.com/watch?v=i2yscjyIBsk</a></p>\n"


I want output as
https://www.youtube.com/watch?v=i2yscjyIBsk


So, how I can I achieve it.

I have tried

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


And tried this regex:
"<a[^>]+href=\"(.*?)\"[^>]*>.*?</a>"


But still I can't figure it out.

Answer

Try below code please:

let string = "<p><a href=\"https://www.youtube.com/watch?v=i2yscjyIBsk\">https://www.youtube.com/watch?v=i2yscjyIBsk</a></p>\n"
let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print("string: \(str)")

Output:

string: https://www.youtube.com/watch?v=i2yscjyIBsk
Comments