我只想按照以下代码提取网站的链接:
import UIKit
import Foundation
func regMatchGroup(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
var internalString = [String]()
for result in results {
for var i = 0; i < result.numberOfRanges; ++i{
internalString.append(nsString.substringWithRange(result.rangeAtIndex(i)))
}
}
return internalString
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
// USAGE:
let textsearch = "mohamed amine ammach <img alt='http://fb.com' /> hhhhhhhhhhh <img alt='http://google.com' />"
let matches = regMatchGroup("alt='(.*?)'", text: textsearch)
if (matches.count > 0) // If we have matches....
{
for (var i=0;i < matches.count;i++) {
print(matches[i])
}
}
Playgrond打印以下内容:
alt='http://fb.com'
http://fb.com
alt='http://google.com'
http://google.com
但我只想获取:
http : //fb.com
http://google.com,
这里有人可以帮助我解决此问题吗?,我将不胜感激
您需要知道该NSTextCheckingResult.rangeAtIndex(_:)
返回的范围与索引为0的整个正则表达式模式匹配。
在您的情况下:
rangeAtIndex(0)
->范围alt='(.*?)'
->alt='http://fb.com'
rangeAtIndex(1)
->范围(.*?)
->http://fb.com
因此,在生成匹配的String时,您需要跳过索引值0。
尝试将最里面的for语句更改为:
for i in 1 ..< result.numberOfRanges { //start index from 1
internalString.append(nsString.substringWithRange(result.rangeAtIndex(i)))
}
(您还需要知道一件事,即不赞成使用C样式的语句。)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句