如果通过Alamofire抓取到了一个html页面, 想从页面里,找到某组数字的最大值,可以通过正则表达式,找到所有数字,然后对比.
var baseurl = "http://www.xxx.com/book/"
var html = "1"
Alamofire.request(baseurl).responseJSON { response in
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
//下面的匹配表达式里,book后面的6位数字,就是我想找的数字
do {
let r = "target=\"_blank\" href=\"http://www.xxx.com/book[0-9]{6}"
let regex = try NSRegularExpression(pattern: r, options: NSRegularExpression.Options.caseInsensitive)
//utf8Text即是html页面的data
let res = regex.matches(in: utf8Text, options: NSRegularExpression.MatchingOptions(rawValue:0), range: NSMakeRange(0, utf8Text.characters.count))
//(utf8Text as NSString).substring(with: checkingRes.range) 是通过匹配模式匹配到的所有字符串. 通过字符串截取,取得最后的6位数字
for checkingRes in res {
print(((utf8Text as NSString).substring(with: checkingRes.range) as NSString).substring(from: 47))
}
}catch {
print(error)
}
}
}
网友评论