You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

32 lines
884 B

  1. //
  2. // Regex.swift
  3. // Kaleidoscope
  4. //
  5. // Created by Matthew Cheok on 15/11/15.
  6. // Copyright © 2015 Matthew Cheok. All rights reserved.
  7. //
  8. import Foundation
  9. var expressions = [String: NSRegularExpression]()
  10. public extension String {
  11. func match(regex: String) -> (String, CountableRange<Int>)? {
  12. let expression: NSRegularExpression
  13. if let exists = expressions[regex] {
  14. expression = exists
  15. } else {
  16. do {
  17. expression = try NSRegularExpression(pattern: "^\(regex)", options: [])
  18. expressions[regex] = expression
  19. } catch {
  20. return nil
  21. }
  22. }
  23. let range = expression.rangeOfFirstMatch(in: self, options: [], range: NSRange(0 ..< self.utf16.count))
  24. if range.location != NSNotFound {
  25. return ((self as NSString).substring(with: range), range.location ..< range.location + range.length )
  26. }
  27. return nil
  28. }
  29. }