Advertisement
Guest User

Untitled

a guest
Oct 22nd, 2016
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. //
  2. // Regex.swift
  3. // ha1fRegex
  4. //
  5. // Created by はるふ on 2016/09/30.
  6. // Copyright © 2016年 はるふ. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10.  
  11. struct Regex {
  12.  
  13. struct Match {
  14. var wholeString = ""
  15. var groups = [String]()
  16.  
  17. init(wholeString: String, groups: [String]) {
  18. self.wholeString = wholeString
  19. self.groups = groups
  20. }
  21.  
  22. init(text: NSString, result res: NSTextCheckingResult) {
  23. let components = (0..<res.numberOfRanges).map { text.substring(with: res.rangeAt($0)) }
  24. self.wholeString = components[0]
  25. self.groups = components.dropFirst().map { $0 }
  26. }
  27. }
  28.  
  29. fileprivate let regex: NSRegularExpression
  30.  
  31. init(_ pattern: String, options: NSRegularExpression.Options = []) throws {
  32. do {
  33. self.regex = try NSRegularExpression(pattern: pattern, options: options)
  34. }
  35. }
  36.  
  37. func firstMatch(_ string: String, range: NSRange? = nil, options: NSRegularExpression.MatchingOptions = []) -> Match? {
  38. let targetRange = range ?? string.wholeNSRange()
  39. let nsstring = string as NSString
  40. if let res = self.regex.firstMatch(in: string, options: options, range: targetRange) {
  41. return Regex.Match(text: nsstring, result: res)
  42. } else {
  43. return nil
  44. }
  45. }
  46.  
  47. func matches(_ string: String, range: NSRange? = nil, options: NSRegularExpression.MatchingOptions = []) -> [Match] {
  48. let targetRange = range ?? string.wholeNSRange()
  49. let nsstring = string as NSString
  50. return self.regex.matches(in: string, options: options, range: targetRange).map { res in
  51. return Regex.Match(text: nsstring, result: res)
  52. }
  53. }
  54. }
  55.  
  56. extension String {
  57. fileprivate func wholeRange() -> Range<String.Index> {
  58. return Range(uncheckedBounds: (self.startIndex, self.endIndex))
  59. }
  60.  
  61. fileprivate func wholeNSRange() -> NSRange {
  62. return NSRange(location: 0, length: self.characters.count)
  63. }
  64.  
  65. func replace(_ regex: Regex, template: String, range: NSRange? = nil, options: NSRegularExpression.MatchingOptions = []) -> String {
  66. let targetRange = range ?? self.wholeNSRange()
  67. return regex.regex.stringByReplacingMatches(in: self, options: options, range: targetRange, withTemplate: template)
  68. }
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement