I'm currently working with NSRegularExpressions
(regex
), which I'm building a markdown regex
.
I think that my approach on the way to change the text that matches the regex
isn't the best one, and here's why.
I have created the following, as example:
UITextViewDelegate
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
regularExpression()
return true
}
func regularExpression() {
// Some other regular expressions....
let boldPattern = "\\*{2}([\\w\\d ]+)\\*{2}"
do {
let regex = try NSRegularExpression(pattern: boldPattern)
let results = regex.matches(in: str, range: NSRange(str.startIndex..., in: str))
_ = results.map {
self.applyAttributes(toRange: $0.range, withType: .bold)
}
} catch let err{
print("error:", err.localizedDescription)
}
}
As you see above, in order for me to update the text as soon as the user types, I'm currently going through the text, for each inserted character, and analyze if there's any matching pattern (in this case to bold as ** some text **);
By doing this, as I go through typing the CPU usage goes from 3% to 25%, thus I think this isn't the best approach to take in.
What would be the best approach to apply NSRegularExpressions
on-the-fly, as the user types? - is the current one I'm using the best one?
Thank you