Skip to content

Instantly share code, notes, and snippets.

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 maxhis/8312d768cbb3eb2af656 to your computer and use it in GitHub Desktop.
Save maxhis/8312d768cbb3eb2af656 to your computer and use it in GitHub Desktop.
Swift extension to NSMutableAttributedString adding methods for highlighting and replacing substrings (swift 2.0 supportted)
extension NSMutableAttributedString {
func highlightStrings(stringToHighlight:String, usingRegex:Bool = false) {
var useRegex:NSRegularExpressionOptions?
if !usingRegex {
useRegex = NSRegularExpressionOptions.IgnoreMetacharacters
}
let exp = try! NSRegularExpression(pattern: stringToHighlight, options: useRegex!)
let arr = exp.matchesInString(self.string, options: [], range:NSRange(location: 0, length: self.length))
for s in arr {
self.addAttribute(NSBackgroundColorAttributeName, value: UIColor.greenColor(), range: s.range)
}
}
func replaceStrings(find:String, replace:String, usingRegex:Bool = false) {
// var useRegex:NSRegularExpressionOptions?
// if !usingRegex {
// useRegex = NSRegularExpressionOptions.IgnoreMetacharacters
// }
//
// let exp = try! NSRegularExpression(pattern: find, options: useRegex!)
// let arr = exp.matchesInString(self.string, options: [], range:NSRange(location: 0, length: self.length))
self.mutableString.replaceOccurrencesOfString(find, withString:replace, options:NSStringCompareOptions.RegularExpressionSearch, range:NSRange(location: 0, length: self.length))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment