1

我想从String使用 NSRegularExpression 获取图像的 url。

func findURlUsingExpression(urlString: String){

    do{

        let expression = try NSRegularExpression(pattern: "\\b(http|https)\\S*(jpg|png)\\b", options: NSRegularExpressionOptions.CaseInsensitive)

        let arrMatches = expression.matchesInString(urlString, options: NSMatchingOptions(rawValue: 0), range: NSMakeRange(0, urlString.characters.count))

        for match in arrMatches{

            let matchText = urlString.substringWithRange(Range(urlString.startIndex.advancedBy(match.range.location) ..< urlString.startIndex.advancedBy(match.range.location + match.range.length)))
            print(matchText)
        }

    }catch let error as NSError{

        print(error.localizedDescription)
    }
}

它仅适用于简单字符串,但不适用于HTML String.

工作示例:

let tempString = "jhgsfjhgsfhjgajshfgjahksfgjhs http://jhsgdfjhjhggajhdgsf.jpg jahsfgh asdf ajsdghf http://jhsgdfjhjhggajhdgsf.png"

findURlUsingExpression(tempString)

输出:

http://jhsgdfjhjhggajhdgsf.jpg
http://jhsgdfjhjhggajhdgsf.png

但不适用于这个:http ://www.writeurl.com/text/478sqami3ukuug0r0bdb/i3r86zlza211xpwkdf2m

4

1 回答 1

2

如果您能提供帮助,请不要滚动您自己的正则表达式。最简单和最安全的方法是使用NSDataDetector. 通过使用NSDataDetector,您可以利用预先构建的、大量使用的解析工具,该工具应该已经消除了大部分错误。

这是一篇很好的文章:NSData​Detector

NSDataDetector 是 NSRegularExpression 的子类,但它不是在 ICU 模式上进行匹配,而是检测半结构化信息:日期、地址、链接、电话号码和交通信息。

import Foundation

let tempString = "jhgsfjhgsfhjgajshfgjahksfgjhs http://example.com/jhsgdfjhjhggajhdgsf.jpg jahsfgh asdf ajsdghf http://example.com/jhsgdfjhjhggajhdgsf.png"

let types: NSTextCheckingType = [.Link]
let detector = try? NSDataDetector(types: types.rawValue)
detector?.enumerateMatchesInString(tempString, options: [], range: NSMakeRange(0, (tempString as NSString).length)) { (result, flags, _) in
  if let result = result?.URL {
    print(result)
  }
}

// => "http://example.com/jhsgdfjhjhggajhdgsf.jpg"
// => "http://example.com/jhsgdfjhjhggajhdgsf.png"

该示例来自该站点,适用于搜索链接。

于 2016-04-05T10:56:40.547 回答