【问题标题】:Find String from String using NSRegularExpression Swift使用 NSRegularExpression Swift 从字符串中查找字符串
【发布时间】:2016-07-25 06:02:12
【问题描述】:

我想使用 NSRegularExpression 从String 获取图像的 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

【问题讨论】:

    标签: swift nsregularexpression swift2.2


    【解决方案1】:

    如果您能提供帮助,请不要使用您自己的正则表达式。最简单、最安全的方法是使用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"
    

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

    【讨论】:

    • 我会尽力让你知道的!
    • 它可以工作但返回错误的链接 - http://i-wallpapers.blogspot.com/2011/12/christmas-iphone-wallpapers.html&amp;quot;,imgurl:&amp;quot;http://2.bp.blogspot.com/-w6JW7Dif8kc/TvDIZcOX7nI/AAAAAAAAAQg/9-7TXCZlutM/s1600/iphone_christmas_wallpaper+%25282%2529.jpg
    • 这是您要解析的字符串,还是您正在访问以获取要解析的数据的网站?
    • 刚才我尝试从这里获取URL! http://www.bing.com/images/async?q=Wallpapers%20Christmas%20Wallpapers&amp;async=content&amp;first=1&amp;count=35&amp;dgsrr=true&amp;qft=+filterui:imagesize-large+filterui:aspect-tall
    • 当我访问该链接时,我没有得到任何可解析的 HTML 内容,只有一些结构。
    猜你喜欢
    • 1970-01-01
    • 2011-09-29
    • 2014-07-01
    • 2011-12-05
    • 1970-01-01
    • 2012-01-18
    • 1970-01-01
    • 2016-06-07
    • 2014-01-17
    相关资源
    最近更新 更多