Skip to content

Instantly share code, notes, and snippets.

@to4iki
Created July 18, 2016 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save to4iki/10fdf4920fc100f1b3cbec02cfb376c0 to your computer and use it in GitHub Desktop.
Save to4iki/10fdf4920fc100f1b3cbec02cfb376c0 to your computer and use it in GitHub Desktop.
simple regex
import Foundation
/// See also
// http://qiita.com/tsuruchika/items/9ca9c4811e1f28b9417c
// http://qiita.com/moaible/items/85d80173bb8ed7f64b74
// http://fromatom.hatenablog.com/entry/2015/07/15/192328
public struct Regex {
private let pattern: String
private let internalExpression: NSRegularExpression
public init(_ pattern: String) {
self.pattern = pattern
do {
self.internalExpression = try NSRegularExpression(pattern: pattern, options: [.CaseInsensitive])
} catch let error as NSError {
print(error.localizedDescription)
self.internalExpression = NSRegularExpression()
}
}
public func isMatch(input: String) -> Bool {
let matches = internalExpression.matchesInString(input, options: [], range: NSRange(location: 0, length: input.characters.count))
return matches.count > 0
}
public func matches(input: String) -> [String]? {
guard isMatch(input) else { return nil }
let matches = internalExpression.matchesInString(input, options: [], range: NSRange(location: 0, length: input.characters.count))
return (0..<matches.count).reduce([]) { (acc: [String], n: Int) -> [String] in
acc + [(input as NSString).substringWithRange(matches[n].range)]
}
}
public func replace(input: String, after: String) -> String {
guard let matches = matches(input) else { return input }
return (0..<matches.count).reduce(input) { (acc: String, n: Int) -> String in
acc.stringByReplacingOccurrencesOfString(matches[n], withString: after, options: [], range: nil)
}
}
}
infix operator =~ {}
public func =~ (input: String, pattern: String) -> Bool {
return Regex(pattern).isMatch(input)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment