Created
November 14, 2016 20:36
-
-
Save odrobnik/f2d058dde6007f33694454582cab5553 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
extension NSRegularExpression | |
{ | |
public func substitutingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], subsituated substitution: @escaping (NSTextCheckingResult)->(String?)) -> String | |
{ | |
let nsString = string as NSString | |
let length = nsString.length | |
let entireString = NSRange(location: 0, length: length) | |
var tmpStr = "" | |
var index = 0 | |
let semaphore = DispatchSemaphore(value: 0) | |
let assemblyQueue = DispatchQueue(label: "Assembly Queue") | |
DispatchQueue.global(qos: .utility).async { | |
defer { | |
assemblyQueue.async { | |
semaphore.signal() | |
} | |
} | |
let matches = self.matches(in: string, options: options, range: entireString) | |
guard matches.count > 0 else | |
{ | |
tmpStr = string | |
return | |
} | |
for match in matches | |
{ | |
assemblyQueue.async { | |
let substitutedRange = match.rangeAt(match.numberOfRanges-1) | |
// append part until match | |
if substitutedRange.location > index | |
{ | |
let substring = nsString.substring(with: NSRange(location: index, length: substitutedRange.location - index)) | |
tmpStr += substring | |
} | |
} | |
assemblyQueue.async | |
{ | |
let substitutedRange = match.rangeAt(match.numberOfRanges-1) | |
if let newString = substitution(match) | |
{ | |
tmpStr += newString | |
} | |
else | |
{ | |
let substring = nsString.substring(with: NSRange(location: index, length: substitutedRange.location - index)) | |
tmpStr += substring | |
} | |
index = NSMaxRange(substitutedRange) | |
} | |
} | |
// append suffix if necessary | |
assemblyQueue.async { | |
if index < length | |
{ | |
let substring = nsString.substring(with: NSRange(location: index, length: length - index)) | |
tmpStr += substring | |
} | |
} | |
} | |
semaphore.wait() | |
return tmpStr | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment