【问题标题】:extract exact links from string using Regex in swift 2.2在 swift 2.2 中使用正则表达式从字符串中提取精确链接
【发布时间】:2016-08-05 23:33:44
【问题描述】:


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

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

    }
}

游乐场打印以下内容:

alt='http://fb.com'
http://fb.com
alt='http://google.com'
http://google.com

但我只想得到:
http://fb.com
http://google.com
有人可以帮我解决这个问题吗?,我将不胜感激

【问题讨论】:

  • 您的结果在第一个捕获组中

标签: regex swift string extract


【解决方案1】:

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

在你的情况下:

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

rangeAtIndex(1) -> (.*?) 的范围 -> http://fb.com

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

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

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

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

【讨论】:

    猜你喜欢
    • 2020-12-16
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-17
    • 2018-06-23
    相关资源
    最近更新 更多