我只想提取以下代码的网站链接:

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)的范围
因此,在生成匹配字符串时,需要跳过索引值0。
尝试将语句的内部most更改为:

            for i in 1 ..< result.numberOfRanges { //start index from 1
                internalString.append(nsString.substringWithRange(result.rangeAtIndex(i)))
            }

(您还需要知道一件事,c-style for语句已被弃用。)

09-29 19:34