Skip to content

Instantly share code, notes, and snippets.

@eddieespinal
Created November 12, 2015 18:56
Show Gist options
  • Select an option

  • Save eddieespinal/e71aa0ffaa82fc414687 to your computer and use it in GitHub Desktop.

Select an option

Save eddieespinal/e71aa0ffaa82fc414687 to your computer and use it in GitHub Desktop.

Revisions

  1. eddieespinal created this gist Nov 12, 2015.
    17 changes: 17 additions & 0 deletions NSRegularExpression
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,17 @@
    let searchString = "this"
    let baseString = "This is some string that contains the word \"this\" more than once. This substring has multiple cases. ThisthisThIs."

    let attributed = NSMutableAttributedString(string: baseString)

    var error: NSError?
    let regex = NSRegularExpression(pattern: searchString, options: .CaseInsensitive, error: &error)

    if let regexError = error {
    println("Oh no! \(regexError)")
    } else {
    for match in regex?.matchesInString(baseString, options: NSMatchingOptions.allZeros, range: NSRange(location: 0, length: baseString.utf16Count)) as [NSTextCheckingResult] {
    attributed.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: match.range)
    }

    textView.attributedText = attributed
    }