From a2dcbd43400120f4822f4ef467ba174001ab62ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pedro=20Jose=CC=81=20Pereira=20Vieito?= Date: Tue, 17 Apr 2018 01:27:46 +0200 Subject: [PATCH] Fixed string NSRange NSRange uses UTF-16 while the implementation was using UTF-8. --- .gitignore | 1 + Sources/Regex.swift | 16 +++++++++------- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/.gitignore b/.gitignore index bea0268..86f6a1c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .DS_Store /.build /Packages +/Package.resolved /*.xcodeproj .ipynb_checkpoints diff --git a/Sources/Regex.swift b/Sources/Regex.swift index 1c03e2a..2479556 100644 --- a/Sources/Regex.swift +++ b/Sources/Regex.swift @@ -39,10 +39,15 @@ struct Regex { extension String { + + /// NSRange of the full string. + private var fullRange: NSRange { + return NSRange(self.startIndex.. Bool { - let range: NSRange = NSMakeRange(0, utf8.count) if let regex = pattern.regex { - let matches = regex.matches(in: self, options: pattern.matchingOptions, range: range) + let matches = regex.matches(in: self, options: pattern.matchingOptions, range: self.fullRange) return matches.count > 0 } return false @@ -53,11 +58,8 @@ extension String { } func replaceRegex(_ pattern: Regex, template: String) -> String { - if self.matchRegex(pattern) { - let range: NSRange = NSMakeRange(0, utf8.count) - if let regex = pattern.regex { - return regex.stringByReplacingMatches(in: self, options: pattern.matchingOptions, range: range, withTemplate: template) - } + if self.matchRegex(pattern), let regex = pattern.regex { + return regex.stringByReplacingMatches(in: self, options: pattern.matchingOptions, range: self.fullRange, withTemplate: template) } return self }