Advertisement
Guest User

Untitled

a guest
Dec 11th, 2016
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. // MARK: - Regular Expression
  2. private extension String
  3. {
  4. func regexp(_ pattern: String) -> NSRegularExpression {
  5. do {
  6. let regexp: NSRegularExpression = try NSRegularExpression(pattern: pattern, options: [NSRegularExpression.Options.caseInsensitive])
  7. return regexp
  8. } catch {
  9. fatalError("regular expression pattern is invalid.")
  10. }
  11. }
  12. }
  13.  
  14. // MARK: - Regular Expression
  15. public extension String
  16. {
  17. public func regexMatched(withPattern pattern: String) -> Bool {
  18. let regexp: NSRegularExpression = self.regexp(pattern)
  19. return 0 < regexp.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: (self as NSString).length))
  20. }
  21.  
  22. public func regexStrings(withPattern pattern: String) -> [String] {
  23. let regexp: NSRegularExpression = self.regexp(pattern)
  24. let matches: [NSTextCheckingResult] = regexp.matches(in: self, options: [], range: NSRange(location: 0, length: (self as NSString).length))
  25. let result: [String] = matches.map { (match: NSTextCheckingResult) in
  26. (self as NSString).substring(with: match.range)
  27. }
  28. return result
  29. }
  30.  
  31. public func regexReplace(withPattern pattern: String, replace: String) -> String
  32. {
  33. let regexp: NSRegularExpression = self.regexp(pattern)
  34. let matches: [NSTextCheckingResult] = regexp.matches(in: self, options: [], range: NSRange(location: 0, length: (self as NSString).length))
  35. var result: String = self
  36. matches.reversed().forEach { (match: NSTextCheckingResult) in
  37. result = (result as NSString).replacingCharacters(in: match.range, with: replace)
  38. }
  39. return result
  40. }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement