Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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