Last active
July 3, 2017 05:15
-
-
Save Qata/8695662c767a8a41e72ac37f4d7e450a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// RegexKit.swift | |
// RegexKit | |
// | |
// Created by Charlotte Tortorella on 3/7/17. | |
// Copyright © 2017 Monadic Consulting. All rights reserved. | |
// | |
import Foundation | |
indirect enum Regex { | |
case contains(String) | |
case begins(with: String) | |
case ends(with: String) | |
case has(CharacterSet) | |
case not(Regex) | |
case or(Regex, Regex) | |
case xor(Regex, Regex) | |
case and(Regex, Regex) | |
func evaluate(against target: String) -> Bool { | |
switch self { | |
case .contains(let string): | |
return target.contains(string) | |
case .begins(with: let string): | |
return target.hasPrefix(string) | |
case .ends(with: let string): | |
return target.hasSuffix(string) | |
case .has(let set): | |
return target.unicodeScalars.contains(where: set.contains(_:)) | |
case .not(let regex): | |
return !regex.evaluate(against: target) | |
case .or(let lhs, let rhs): | |
return lhs.evaluate(against: target) || rhs.evaluate(against: target) | |
case .xor(let lhs, let rhs): | |
return lhs.evaluate(against: target) != rhs.evaluate(against: target) | |
case .and(let lhs, let rhs): | |
return lhs.evaluate(against: target) && rhs.evaluate(against: target) | |
} | |
} | |
} | |
extension String { | |
func match(regex: Regex) -> Bool { | |
return regex.evaluate(against: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment