Skip to content

Instantly share code, notes, and snippets.

@aquajach
Last active June 2, 2021 21:31
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aquajach/4d9398b95a748fd37e88 to your computer and use it in GitHub Desktop.
Save aquajach/4d9398b95a748fd37e88 to your computer and use it in GitHub Desktop.
Swift: Highlight matched text in String between square brackets
import UIKit
extension NSMutableAttributedString {
func highlightTarget(target: String, color: UIColor) -> NSMutableAttributedString {
let targetValue = String(target.characters.dropFirst().dropLast())
let regPattern = "\\[\(targetValue)\\]"
if let regex = try? NSRegularExpression(pattern: regPattern, options: []) {
let matchesArray = regex.matchesInString(self.string, options: [], range: NSRange(location: 0, length: self.length))
for match in matchesArray {
let attributedText = NSMutableAttributedString(string: targetValue)
attributedText.addAttribute(NSForegroundColorAttributeName, value: color, range: NSRange(location: 0, length: attributedText.length))
self.replaceCharactersInRange(match.range, withAttributedString: attributedText)
}
}
return self
}
}
//Usage
let attributedString = NSMutableAttributedString(string: "Hello, [swift].[playground]")
if let textInArray = ["swift", "playground", "others"] {
for text in textInArray {
attributedString.highlightTarget(text, color: UIColor.blueColor())
}
}
@siddheshredkar
Copy link

//swift 5

extension NSMutableAttributedString {

func highlightTarget(target: String, color: UIColor) -> NSMutableAttributedString {
    let targetValue = String(target.dropFirst().dropLast())
    let regPattern = "\\[\(targetValue)\\]"
    if let regex = try? NSRegularExpression(pattern: regPattern, options: []) {
        let matchesArray = regex.matches(in: self.string, options: [], range: NSRange(location: 0, length: self.length))
        for match in matchesArray {
            let attributedText = NSMutableAttributedString(string: targetValue)
            attributedText.addAttribute(NSAttributedString.Key.foregroundColor, value: color, range: NSRange(location: 0, length: attributedText.length))
            self.replaceCharacters(in: match.range, with: attributedText)
        }
    }
    return self
}

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment