找到一个字符串并提取后面的字符

时间:2017-04-22 21:55:40

标签: swift string substring

我在用户提交信息后访问网页的HTML。

如果我有......

var htmlString = "This is the massive HTML string - it has lots of characters "FindStringDetails"<123789456.123456>  This is a massive HTML string - "
var findString = "FindStringDetails\"<"

是否有合适的方法可以提取“FindStringDetails”之后的数字&lt;给我123789456.123456?

1 个答案:

答案 0 :(得分:0)

import Foundation

var htmlString = "This is the massive HTML string - it has lots of characters \"FindStringDetails\"<123789456.123456>  This is a massive HTML string - "
var findString = "FindStringDetails\"<"

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = NSString(string: self)
        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))
                : ""
            }
        }
    }
}

let m = htmlString.matchingStrings(regex: "\(findString)(\\d+)\\.(\\d+)")

print(m[0][1]) // 123789456
print(m[0][2]) // 123456

(代码改编自here。)