Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sketchytech/7cd6ab241a22fc2a3ffc to your computer and use it in GitHub Desktop.
Save sketchytech/7cd6ab241a22fc2a3ffc to your computer and use it in GitHub Desktop.
Swift extension to NSMutableAttributedString adding methods for highlighting and replacing substrings
extension NSMutableAttributedString {
func highlightStrings(stringToHighlight:String, usingRegex:Bool = false) {
var useRegex:NSRegularExpressionOptions?
if !usingRegex {
useRegex = NSRegularExpressionOptions.IgnoreMetacharacters
}
let exp = NSRegularExpression(pattern: stringToHighlight, options: useRegex ?? nil, error: nil)
let arr = exp.matchesInString(self.string, options: nil, 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 = NSRegularExpression(pattern: find, options: useRegex ?? nil, error: nil)
let arr = exp.matchesInString(self.string, options: nil, range:NSRange(location: 0, length: self.length))
self.mutableString.replaceOccurrencesOfString(find, withString:replace, options:NSStringCompareOptions.RegularExpressionSearch, range:NSRange(location: 0, length: self.length))
}
}
@maxhis
Copy link

maxhis commented Jan 7, 2016

Not working with swift 2.0?

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