Skip to content

Instantly share code, notes, and snippets.

@erica
Last active March 8, 2018 11:57
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save erica/ccf504618840dd48e65c to your computer and use it in GitHub Desktop.
Save erica/ccf504618840dd48e65c to your computer and use it in GitHub Desktop.
import Foundation
// Extend String to support regex searching by conforming
// to CustomStringConvertible
extension String: CustomStringConvertible {
public var description: String {return self}
}
// Regex support for keys
public extension Dictionary where Key: CustomStringConvertible {
/// Return keys that match the supplied Key expressed as string
public subscript (regexKeys regex: Key) -> [Key] {
get {
// I went with a pretty flexible case insensitive
// search here. Tweak as desired.
let options: NSStringCompareOptions = [
.RegularExpressionSearch,
.CaseInsensitiveSearch,
.DiacriticInsensitiveSearch
]
let stringRex = String(regex)
return keys.filter({
// Thanks Patrick Smith, http://twitter.com/concreteniche/status/701906479645794304
return ($0.description as NSString)
.rangeOfString(stringRex, options: options)
.location != NSNotFound
})
}
}
/// Return values that match the regex Key
public subscript (regex regex: Key) -> [Value] {
return self[regexKeys: regex].flatMap({ self[$0] })
}
}
let sample = [
"monday": "mValue",
"tuesday": "tValue",
"weds": "wValue",
"thursday": "thValue"]
print(sample[regex: ".*day"])
print(sample[regexKeys: ".*day"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment