2015-07-30 14 views
20

Ricevo una stringa da html parse che è;Swift Ottieni una stringa tra 2 stringhe in una stringa

string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" 

il mio codice è qualcosa di simile

var startIndex = text.rangeOfString("'") 
var endIndex = text.rangeOfString("',") 
var range2 = startIndex2...endIndex 
substr= string.substringWithRange(range) 

non sono sicuro se la mia seconda stringa scissione dovrebbe essere " '" o "',"

voglio che il mio risultato come

substr = "Info/99/something" 
+0

C'è sempre la stessa lunghezza (ad esempio il 1) - o è diverso? "Info/..." è sempre lo stesso? Pls condivide altre stringhe, per trovare il modo migliore per ottenere la stringa. – derdida

+0

javascript: getInfo (1, 'Info/123/somethingelse', 'City2 hall3', 456,789); – alp

risposta

15

userei un'espressione regolare per estrarre sottostringhe da ingresso complesso come questo.

Swift 3.1:

let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" 

if let match = test.range(of: "(?<=')[^']+", options: .regularExpression) { 
    print(test.substring(with: match)) 
} 

// Prints: Info/99/something 

Swift 2.0:

let test = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" 

if let match = test.rangeOfString("(?<=')[^']+", options: .RegularExpressionSearch) { 
    print(test.substringWithRange(match)) 
} 

// Prints: Info/99/something 
4

Questo funziona se è sempre la seconda suddivisione:

let subString = split(string, isSeparator: "'")[1] 
+0

lascia subString = split (testo, "'"); restituisce subString [1]; in questo codice dà errore "Argomento mancante per parametro" isSeparator "in chiamata" – alp

3

È possibile utilizzare var arr = str.componentsSeparatedByString(",") come frazione di secondo che restituirà si serie

+0

im facendo questo processo di sottostringa in una funzione, quando chiamo return subString [1] dà errore "non può pedici un valore di tipo '[String]' con un indice di tipo()." se chiamo subString [0] funziona come previsto – alp

3

considerare l'utilizzo di un'espressione regolare per abbinare tutto tra virgolette singole.

let string = "javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" 

let pattern = "'(.+?)'" 
let regex = NSRegularExpression(pattern: pattern, options: nil, error: nil) 
let results = regex!.matchesInString(string, options: nil, range: NSMakeRange(0, count(string))) as! [NSTextCheckingResult] 

let nsstring = string as NSString 
let matches = results.map { result in return nsstring.substringWithRange(result.range)} 

// First match 
println(matches[0]) 
44

Swift 4

extension String { 

    func slice(from: String, to: String) -> String? { 

     return (range(of: from)?.upperBound).flatMap { substringFrom in 
      (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in 
       String(self[substringFrom..<substringTo]) 
      } 
     } 
    } 
} 

Swift 3

extension String { 

    func slice(from: String, to: String) -> String? { 

     return (range(of: from)?.upperBound).flatMap { substringFrom in 
      (range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in 
       substring(with: substringFrom..<substringTo) 
      } 
     } 
    } 
} 

Vecchia risposta:

import Foundation 

extension String { 
    func sliceFrom(start: String, to: String) -> String? { 
    return (rangeOfString(start)?.endIndex).flatMap { sInd in 
     (rangeOfString(to, range: sInd..<endIndex)?.startIndex).map { eInd in 
     substringWithRange(sInd..<eInd) 
     } 
    } 
    } 
} 

"javascript:getInfo(1,'Info/99/something', 'City Hall',1, 99);" 
    .sliceFrom("'", to: "',") 
+0

Questo è fantastico! Grazie! – CodyMace

+0

@oisdk funziona se abbiamo bisogno di tagliare una stringa alla fine della stringa? Es: "blabla popo titi toto" -> slice (da "popo" a: endOfString)? – Makaille

0

Versione Swift 4 di @litso. Per trovare tutti i valori nel testo

func find(inText text: String, pattern: String) -> [String]? { 
     do { 
      let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive) 
      let result = regex.matches(in: text, options: .init(rawValue: 0), range: NSRange(location: 0, length: text.count)) 

      let matches = result.map { result in 
       return (text as NSString).substring(with: result.range) 
      } 

      return matches 
     } catch { 
      print(error) 
     } 
     return nil 
    } 
Problemi correlati