第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

快速提取正則匹配

快速提取正則匹配

收到一只叮咚 2019-06-15 13:31:35
快速提取正則匹配我想從匹配regex模式的字符串中提取子字符串。所以我在找這樣的東西:func matchesForRegexInText(regex: String!, text: String!) -> [String] {    ???}所以這就是我所擁有的:func matchesForRegexInText(regex: String!, text: String!) -> [String] {     var regex = NSRegularExpression(pattern: regex,          options: nil, error: nil)     var results = regex.matchesInString(text,          options: nil, range: NSMakeRange(0, countElements(text)))              as Array<NSTextCheckingResult>     /// ???     return ...}問題是,matchesInString給我一個數(shù)組NSTextCheckingResult,在哪里NSTextCheckingResult.range是類型的NSRange.NSRange是不相容的Range<String.Index>,所以它阻止了我使用text.substringWithRange(...)知道如何在沒有太多代碼行的情況下快速實現(xiàn)這個簡單的事情嗎?
查看完整描述

3 回答

?
慕少森

TA貢獻2019條經(jīng)驗 獲得超9個贊

我的答案建立在給定的答案之上,但通過添加額外的支持,使正則表達式匹配更加健壯:

  • 返回不僅匹配,而且

    返回所有捕獲組

    對于每一場比賽(見下面的例子)
  • 而不是返回一個空數(shù)組,這個解決方案

    支持可選匹配

  • do/catch

    通過不打印到控制臺和

    使用guard構(gòu)造

  • matchingStrings

    作為

    擴展到String

SWIFT 4.2

//: Playground - noun: a place where people can playimport Foundationextension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.range(at: $0).location != NSNotFound
                    ? nsString.substring(with: result.range(at: $0))
                    : ""
            }
        }
    }}"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]"prefix12"
    .matchingStrings(regex: "(?:prefix)?([0-9]+)")// Prints: [["prefix12", "12"]]"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
    // Prints: [["12", "12"]], other answers return an empty array here// Safely accessing the capture of the first match (if any):let 
    number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]// Prints: Optional("12")

SWIFT 3

//: Playground - noun: a place where people can playimport Foundationextension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.rangeAt($0).location != NSNotFound
                    ? nsString.substring(with: result.rangeAt($0))
                    : ""
            }
        }
    }}"prefix12 aaa3 prefix45".matchingStrings(regex: "fix([0-9])([0-9])")// Prints: [["fix12", "1", "2"], ["fix45", "4", "5"]]"prefix12".
    matchingStrings(regex: "(?:prefix)?([0-9]+)")// Prints: [["prefix12", "12"]]"12".matchingStrings(regex: "(?:prefix)?([0-9]+)")
    // Prints: [["12", "12"]], other answers return an empty array here// Safely accessing the capture of the first match (if any):let 
    number = "prefix12suffix".matchingStrings(regex: "fix([0-9]+)su").first?[1]// Prints: Optional("12")

SWIFT 2

extension String {
    func matchingStrings(regex: String) -> [[String]] {
        guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] }
        let nsString = self as NSString
        let results  = regex.matchesInString(self, options: [], range: NSMakeRange(0, nsString.length))
        return results.map { result in
            (0..<result.numberOfRanges).map {
                result.rangeAtIndex($0).location != NSNotFound
                    ? nsString.substringWithRange(result.rangeAtIndex($0))
                    : ""
            }
        }
    }}


查看完整回答
反對 回復(fù) 2019-06-15
  • 3 回答
  • 0 關(guān)注
  • 712 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號