Regex 在swift 2.2中使用正则表达式从字符串中提取精确链接

Regex 在swift 2.2中使用正则表达式从字符串中提取精确链接,regex,swift,string,extract,Regex,Swift,String,Extract,我只想按照以下代码提取网站的链接: 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 r


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

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])

    }
}
但我只是想:



这里有人能帮我解决这个问题吗?

我将不胜感激。您需要知道
NSTextCheckingResult.rangeAtIndex(:)
返回与索引为0的整个正则表达式模式相匹配的范围

就你而言:

rangeAtIndex(0)
->
alt='(.*?)的范围http://fb.com“

范围索引(1)
->
(.*)
->
http://fb.com

所以,在生成匹配字符串时,需要跳过索引值0

尝试将最内部的for语句更改为:

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

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

您的结果是第一个捕获组
            for i in 1 ..< result.numberOfRanges { //start index from 1
                internalString.append(nsString.substringWithRange(result.rangeAtIndex(i)))
            }