Skip to content

Instantly share code, notes, and snippets.

@yhkaplan
Last active January 15, 2019 07:20
Show Gist options
  • Save yhkaplan/3e844faed3a43aeacd6836a94e4aa345 to your computer and use it in GitHub Desktop.
Save yhkaplan/3e844faed3a43aeacd6836a94e4aa345 to your computer and use it in GitHub Desktop.
Swifty wrapper for NSRegularExpression
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