Last active
January 15, 2019 07:20
-
-
Save yhkaplan/3e844faed3a43aeacd6836a94e4aa345 to your computer and use it in GitHub Desktop.
Swifty wrapper for NSRegularExpression
This file contains 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
import Foundation | |
struct Regex: ExpressibleByStringLiteral { | |
private let pattern: String | |
private var nsRegularExpression: NSRegularExpression? { | |
return try? NSRegularExpression(pattern: pattern) | |
} | |
typealias StringLiteralType = String | |
init(stringLiteral value: StringLiteralType) { | |
pattern = value | |
} | |
init(_ string: String) { | |
pattern = string | |
} | |
func matches(in string: String) -> [String] { | |
let ranges = nsRegularExpression? | |
.matches(in: string, options: [], range: searchRange(for: string)) | |
.compactMap { Range($0.range, in: string) } | |
?? [] | |
return ranges | |
.map { string[$0] } | |
.map(String.init) | |
} | |
func hasMatch(in string: String) -> Bool { | |
return firstMatch(in: string) != nil | |
} | |
func firstMatch(in string: String) -> String? { | |
guard | |
let match = nsRegularExpression?.firstMatch( | |
in: string, | |
options: [], | |
range: searchRange(for: string) | |
), | |
let matchRange = Range(match.range, in: string) | |
else { | |
return nil | |
} | |
return String(string[matchRange]) | |
} | |
private func searchRange(for string: String) -> NSRange { | |
return NSRange(location: 0, length: string.utf16.count) | |
} | |
} | |
// MARK: Operator related | |
infix operator =~ | |
extension Regex { | |
static func =~ (string: String, regex: Regex) -> Bool { | |
return regex.hasMatch(in: string) | |
} | |
static func =~(regex: Regex, string: String) -> Bool { | |
return regex.hasMatch(in: string) | |
} | |
} | |
//TODO: Add extensions to String | |
/* | |
extension String { | |
func matches(_ regex: Regex) -> [String] { | |
return regex.matches(in: self) | |
} | |
} | |
*/ | |
let regex: Regex = "sheep" | |
let result = regex.matches(in: "shee1p+sheep+sheep") | |
let test = Regex("[1-9]") =~ "hey1sheep" | |
switch "test_string" { | |
case let s where Regex("^test") =~ s: | |
print("ok") | |
default: | |
print("nope") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment