Swift Regular Expressions Example

1. Introduction

Regular Expressions, often abbreviated as regex, are a powerful tool for searching, matching, and manipulating text. Swift leverages the power of the NSRegularExpression class from Foundation to work with regular expressions. Here's a brief primer with examples on how to use regex in Swift.

2. Source Code Example

import Foundation

// 1. Simple text matching
let text = "Swift is amazing!"
let pattern = "amazing"

if text.range(of: pattern, options: .regularExpression) != nil {
    print("Match found!")
}

// 2. Extracting matches
let emailText = "Contact us at contact@example.com"
let emailPattern = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"

if let match = emailText.range(of: emailPattern, options: .regularExpression) {
    let matchedEmail = emailText[match]
    print("Extracted email: \(matchedEmail)")
}

// 3. Replacing substrings using regex
let messyString = "Hey!!! Are you free tomorrow???"
let cleanedString = messyString.replacingOccurrences(of: "[!?]{2,}", with: "", options: .regularExpression)
print(cleanedString)

// 4. Validate string format (e.g., a password)
let password = "Abc@1234"
let passwordPattern = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$"

let passwordRegex = try! NSRegularExpression(pattern: passwordPattern)
if passwordRegex.firstMatch(in: password, options: [], range: NSRange(location: 0, length: password.utf16.count)) != nil {
    print("Valid password format!")
} else {
    print("Invalid password format!")
}

Output:

Match found!
Extracted email: contact@example.com
Hey! Are you free tomorrow?
Valid password format!

3. Step By Step Explanation

1. Simple Text Matching: Using the range(of:options:) method of a string, we can easily search for a substring that matches a given regex pattern.

2. Extracting Matches: We can extract substrings from the text that match a given regex. Here, we extract an email address from the given text.

3. Replacing Substrings Using Regex: The replacingOccurrences(of:with:options:) method allows for powerful transformations. Here, we clean up a string by removing repeated punctuation marks.

4. Validate String Format: Validating text formats is a common use case for regex. In this example, we validate a password to ensure it meets certain criteria (e.g., contains at least one uppercase letter, one lowercase letter, one number, and one special character, and is at least 8 characters long).


Comments