Kodeco Forums

NSRegularExpression Tutorial: Getting Started

Learn how to search, replace, and validate data in your app with this NSRegularExpression tutorial. Includes a handy cheat sheet and playground for you to take home!


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/2018-nsregularexpression-tutorial-getting-started

I would greatly appreciate if this was updated to Swift 2.0. Please and thanks. (Seriously, I would pay like 10$ to get this updated to Swift 2)

EDIT: OK I have figured out the updated code for the Search and Replace Sections (As well as the highlighting text part) If the article writer or whoever wants to update the article let me know but here is the code:

When you create the RegexHelpers.swift file, this is the code:

extension NSRegularExpression {
convenience init?(options: SearchOptions) {
let searchString = options.searchString
let isCaseSensitive = options.matchCase
let isWholeWords = options.wholeWords
let regexOption: NSRegularExpressionOptions = (isCaseSensitive) ? [] : .CaseInsensitive
let pattern = (isWholeWords) ? “\b(searchString)\b” : searchString

    do {
     try self.init(pattern: pattern, options: regexOption)
    } catch {
        print(error)
    }
}

}

For the searchForText function:

func searchForText(searchText: String, replaceWith replacementText: String, inTextView textView: UITextView) {

    let beforeText = textView.text
    let range = NSMakeRange(0, beforeText.characters.count)
    
    if let regex = NSRegularExpression(options: self.searchOptions!) {
        let afterText = regex.stringByReplacingMatchesInString(beforeText, options: [], range: range, withTemplate: replacementText)
        
        textView.text = afterText
    }
}

For the highlighting function

func highlightText(searchText: String, inTextView textView: UITextView) {
let attributedText = textView.attributedText.mutableCopy() as! NSMutableAttributedString

    let attributedTextRange = NSMakeRange(0, attributedText.length)
    
    if let regex =  NSRegularExpression(options: self.searchOptions!){
        let range = NSMakeRange(0, (textView.text.characters.count))
        let matches = regex.matchesInString(textView.text, options: [], range: range)
        
        for match in matches as! [NSTextCheckingResult] {
            let matchRange = match.range
            
            attributedText.addAttribute(NSBackgroundColorAttributeName, value: UIColor.yellowColor(), range: matchRange)
        }
    }
    textView.attributedText = attributedText.copy() as! NSAttributedString
    
}
1 Like

For anyone doing this with Swift 2. You will get an error when you launch the provided projects for lines with “.allZeroes”. (It’ll make sense if you look at the code.) Just replace it with “[ ]” (empty brackets, no quotes). Here is the page I found this on: Problem with swift 2.0 and .allZer… | Apple Developer Forums

I also hope this tutorial will be updated to Swift 2. Also would be great to have a more basic tutorial on Regex, I found this very hard to follow and understand.

I also hope this tutorial will be updated to Swift 3

There is a mistake in Regex example in date of birth:

“^(0[1-9]|1[012])[-/.](0[1-9]|[12][0-9]|3[01])[-/.](19|20)\d\d$” // Date of Birth

has format MM-dd-YYYY and not dd-MM-YYYY as the task asked for

I also hope this tutorial will be updated to Swift 3

This is a great tutorial. But as many have said it has not been updated to Swift 3. But considering Swift 4 will be releasing soon, I (and I’m sure many others) would appreciate an update for either/or both 3 AND 4

For those interested I have found this resource which seems to be designed with Swift 3 in mind. Documentation - Stack Overflow

This tutorial is more than six months old so questions are no longer supported at the moment for it. We will update it as soon as possible. Thank you! :]