Skip to content

Instantly share code, notes, and snippets.

@pablogeek
Last active May 28, 2017 14:45
Show Gist options
  • Save pablogeek/bb611d94f20cb3bcedb32bb70e6518f9 to your computer and use it in GitHub Desktop.
Save pablogeek/bb611d94f20cb3bcedb32bb70e6518f9 to your computer and use it in GitHub Desktop.
Parser Swift
//
// RegexManager.swift
//
// Created by Pablo Martinez on 26/05/2017.
// Copyright © 2017 PabloSoftware. All rights reserved.
//
import Foundation
extension String{
func regexValues<T>(expression: String) -> [T]?{
do{
let regex = try! NSRegularExpression(pattern: expression, options: [])
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.characters.count))
let values = matches.map({ (match) -> T in
return valueTo(value: self.substring(with: range(from: match.rangeAt(1))!))!
})
return values
}
return .none
}
private func valueTo<T>(value: String) -> T?{
switch T.self {
case is Int.Type:
return ParsableInt(v: value).parse().parseString() as? T
case is String.Type:
return value as? T
case is Double.Type:
return ParsableDouble(v: value).parse().parseString() as? T
default:
return .none
}
}
func regexMatches(expression: String) -> Bool{
do{
let regex = try NSRegularExpression(pattern: expression, options: [])
let matches = regex.matches(in: self, options: [], range: NSRange(location: 0, length: self.characters.count))
return matches.count > 0
}catch{
return false
}
}
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
}
protocol Parsable {
associatedtype T
var value: String {get set}
init(value: String)
func parseString() -> T
}
class ParsableGeneric<T: Parsable> {
var value: String
init(v: String) {
value = v
}
func parse() -> T{
return T(value: self.value)
}
}
class ParsableInt: ParsableGeneric<IntParse> {}
struct IntParse: Parsable {
var value: String
func parseString() -> Int {
return Int(value)!
}
typealias T = Int
}
class ParsableDouble: ParsableGeneric<DoubleParse>{}
struct DoubleParse: Parsable {
typealias T = Double
var value: String
func parseString() -> Double {
return Double(value)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment