example ios string swift substring

ios - example - substring to string swift 4



Swift Obtener cadena entre 2 cadenas en una cadena (9)

Estoy obteniendo una cadena de análisis html que es;

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

mi código es algo como

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

no estoy seguro de si mi segunda cadena de división debería ser "''" o "'',"

quiero mi resultado como

substr = "Info/99/something"


Considere usar una expresión regular para unir todo entre comillas simples.

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


En Swift 4 o posterior, puede crear un método de extensión en StringProtocol para admitir también subcadenas. Puede devolver una Substring lugar de una nueva cadena:

edit / u [fecha: Swift 5

let string = "javascript:getInfo(1,''Info/99/something'', ''City Hall'',1, 99);" let substr = string.substring(from: "''") // "Info/99/something'', ''City Hall'',1, 99);" let subString = string.substring(from: "''", to: "'',") // "Info/99/something" let subStringCaseInsensitive = string.substring(from: "''info/", to: "/something", options: .caseInsensitive) // "99"

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 }


Esto funciona si siempre es la segunda división:

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


Puede usar var arr = str.componentsSeparatedByString(",") como su segunda división que le devolverá su matriz


Reescribí una de las mejores respuestas de Swift 4 para comprender que estaba haciendo con el map . Prefiero una versión con guard , IMO

Sería fácil agregar opciones para Búsqueda hacia atrás, etc.

extension String { func slice(from: String, to: String) -> String? { guard let rangeFrom = range(of: from)?.upperBound else { return nil } guard let rangeTo = self[rangeFrom...].range(of: to)?.lowerBound else { return nil } return String(self[rangeFrom..<rangeTo]) } } let test1 = "a[b]c".slice(from: "[", to: "]") // "b" let test2 = "abc".slice(from: "[", to: "]") // nil let test3 = "a]b[c".slice(from: "[", to: "]") // nil let test4 = "[a[b]c]".slice(from: "[", to: "]") // "a[b"


Swift 4.2:

extension StringProtocol { func substring(from start: Self, to end: Self? = nil, options: String.CompareOptions = []) -> SubSequence? { guard let lower = range(of: start, options: options)?.upperBound else { return nil } guard let end = end else { return self[lower...] } guard let upper = self[lower...].range(of: end, options: options)?.lowerBound else { return nil } return self[lower..<upper] } }


Usaría una expresión regular para extraer subcadenas de entradas complejas como esta.

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


Versión Swift 4 de @litso. Para encontrar todos los valores en el texto

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 }


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

Vieja respuesta:

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: "'',")