Skip to content

Instantly share code, notes, and snippets.

@WingCH
Last active June 23, 2019 09:11
Show Gist options
  • Save WingCH/72f763cb7a97ef3f05967b21943a2ddf to your computer and use it in GitHub Desktop.
Save WingCH/72f763cb7a97ef3f05967b21943a2ddf to your computer and use it in GitHub Desktop.
Swift extract regex matches

https://stackoverflow.com/a/40040472/10999568

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.range(at: $0).location != NSNotFound
                    ? nsString.substring(with: result.range(at: $0))
                    : ""
            }
        }
    }
}

大眾點評分享字串:

蒸的好海鲜馆,★★★★☆,¥246/人,蛇口海鲜,南海大道蛇口网谷万融大厦C座G层101http://m.dianping.com/appshare/shop/23995892

var regexed = theString.matchingStrings(regex:"^([^,]+),([^,]+),([^,]+),([^,]+),([^http]*)(.*)")
print(regexed)

[["蒸的好海鲜馆,★★★★☆,¥246/人,蛇口海鲜,南海大道蛇口网谷万融大厦C座G层101http://m.dianping.com/appshare/shop/23995892", "蒸的好海鲜馆", "★★★★☆", "¥246/人", "蛇口海鲜", "南海大道蛇口网谷万融大厦C座G层101", "http://m.dianping.com/appshare/shop/23995892"]]

if !regexed.isEmpty{
    print("Name: \(regexed[0][1])")
    print("Address: \(regexed[0][5])")
    print("Url: \(regexed[0][6])")
}else{
    print("regexed is Empty")
}

Name: 蒸的好海鲜馆

Address: 南海大道蛇口网谷万融大厦C座G层101

Url: http://m.dianping.com/appshare/shop/23995892

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment