Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Created November 14, 2016 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save odrobnik/f2d058dde6007f33694454582cab5553 to your computer and use it in GitHub Desktop.
Save odrobnik/f2d058dde6007f33694454582cab5553 to your computer and use it in GitHub Desktop.
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