Извлечь ссылку из href в Swift - PullRequest
0 голосов
/ 09 мая 2019

Предположим, у меня есть ссылка HTML, как это:

<a href = "https://mitsui-shopping-park.com/lalaport/koshien/" target="_blank"> https://mitsui-shopping-park.com/lalaport / koshien / </a>

Я хочу извлечь:

<a href = "THIS LINK" target="_blank"> NOT THIS LINK </a> 

Я пытался: someString.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil), но это дает мне:

<a href = "NOT THIS LINK" target="_blank"> BUT THIS LINK </a>

Пожалуйста, помогите.

Ответы [ 3 ]

2 голосов
/ 09 мая 2019

Нет необходимости в регулярном выражении, вы можете использовать свойство link приписанной строки.

Во-первых, давайте используем это расширение:

extension String{
    func convert2Html() -> NSAttributedString {

        guard let data = data(using: .utf8) else { return NSAttributedString() }

        do {
            let htmlAttrib = NSAttributedString.DocumentType.html
            return try NSAttributedString(data: data,
                                          options: [.documentType : htmlAttrib],
                                          documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
}

для преобразования String:

let html = "<a href = \"https://mitsui-shopping-park.com/lalaport/koshien/\" target=\"_blank\"> https://mitsui-shopping-park.com/lalaport / koshien / </a>"

в NSAttributedString:

let attrib = html.convert2Html()

А затем распакуйте ссылку следующим образом:

let link = attrib.attribute(.link, at: 0, effectiveRange: nil)

if let url = link as? NSURL, let href = url.absoluteString {
    print(href)  //https://mitsui-shopping-park.com/lalaport/koshien/
}
1 голос
/ 09 мая 2019

Вот одно из возможных решений для захвата значения между href=" и закрывающим ". Это работает только с одним href в строке.

let html = "<a href = \"https://mitsui-shopping-park.com/lalaport/koshien/\" target=\"_blank\"> https://mitsui-shopping-park.com/lalaport / koshien / </a>"

if let hrefRange = html.range(of: "(?:href\\s*=\\s*\")[^\"]*(?:\")", options: .regularExpression) {
    let href = html[hrefRange]
    print(href)
} else {
    print("There is no href")
}

Давайте разберем это регулярное выражение:

Во-первых, давайте удалим лишние \, необходимые в RE, чтобы сделать его строкой Swift значения. Это оставляет нас с:

(?:href\s*=\s*")[^"]*(?:")

Это состоит из трех основных частей:

(?:href\s*=\s*") - the href, optional space, =, optional space, and opening quote
[^"]* - the actual URL - everything that isn't a quote
(?:") - the close quote

Синтаксис (?: ) означает, что содержимое внутри не будет частью возвращаемой строки.

0 голосов
/ 09 мая 2019

Используйте NSRegularExpression.matches для функции группы захвата регулярного выражения.Я всегда использую этот удобный метод расширения:

extension String {
    func capturedGroups(withRegex pattern: String) -> [String?] {
        var results = [String?]()

        var regex: NSRegularExpression
        do {
            regex = try NSRegularExpression(pattern: pattern, options: [])
        } catch {
            return results
        }

        let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.count))

        guard let match = matches.first else { return results }
        let lastRangeIndex = match.numberOfRanges - 1
        guard lastRangeIndex >= 1 else { return results }

        for i in 0...lastRangeIndex {
            let capturedGroupIndex = match.range(at: i)
            if(capturedGroupIndex.length>0)
            {
                let matchedString = (self as NSString).substring(with: capturedGroupIndex)
                results.append(matchedString)
            }
            else
            {
                results.append(nil)
            }
        }

        return results
    }
}

var html = """
<a href = "https://mitsui-shopping-park.com/lalaport/koshien/" target="_blank"> https://mitsui-shopping-park.com/lalaport / koshien / </a>
"""
print(html.capturedGroups(withRegex: "href\\s*=\\s*\"([^\"]+)\"")[1])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...