Regular Expressions in Swift: From Basics to Advanced Examples
Regular expressions (regex) are a powerful tool for working with text, allowing you to search, replace, and validate strings using complex patterns. In Swift for iOS and macOS, working with regex is implemented through the NSRegularExpression class from the Foundation framework. In this article, we'll cover all key aspects: from creating simple patterns to processing results and performance optimization.
This article will be useful both for beginners just getting acquainted with Swift and for experienced developers looking to deepen their knowledge of text processing in iOS/macOS applications.
1. Basics of Working with NSRegularExpression
The NSRegularExpression class is the primary tool for working with regular expressions in Swift. It provides methods for searching, replacing, and extracting data from strings.
1.1. Creating a Regular Expression
To create an NSRegularExpression object, an initializer is used that takes a pattern string and optional flags (NSRegularExpression.Options). The construction is wrapped in try because it can throw an error if the pattern syntax is invalid.
import Foundation
let pattern = "\\\\d{3}-\\\\d{2}-\\\\d{4}" // Example: 123-45-6789do { let regex = try NSRegularExpression(pattern: pattern, options: []) print("Regular expression created successfully")} catch { print("Error in regular expression syntax: \\(error.localizedDescription)")}1.2. Main Options (NSRegularExpression.Options)
Options allow you to change the behavior of the regular expression. Here are the most commonly used ones:
.caseInsensitive— ignore character case (A = a)..allowCommentsAndWhitespace— ignore whitespace and comments in the pattern..dotMatchesLineSeparators— dot (.) also matches line break characters..anchorsMatchLines— the ^ and $ characters match the beginning and end of each line, not the entire string.
Example with the .caseInsensitive option:
let pattern = "hello"let regex = try NSRegularExpression(pattern: pattern, options: .caseInsensitive)let testString = "Hello, World!"let range = NSRange(location: 0, length: testString.utf16.count)if regex.firstMatch(in: testString, options: [], range: range) != nil { print("Match found") // Output: Match found}2. Searching for Matches and Working with Results
After creating a regular expression, you can search for matches in a string. The firstMatch and matches methods are used for this.
2.1. Searching for the First Match
The firstMatch(in:options:range:) method returns the first found match as an NSTextCheckingResult object (or nil if nothing is found).
let text = "My number: 123-45-6789, and also 987-65-4321"let pattern = "\\\\d{3}-\\\\d{2}-\\\\d{4}"let regex = try NSRegularExpression(pattern: pattern, options: [])let range = NSRange(location: 0, length: text.utf16.count)
if let match = regex.firstMatch(in: text, options: [], range: range) { let matchedString = (text as NSString).substring(with: match.range) print("First match: \\(matchedString)") // 123-45-6789}2.2. Searching for All Matches
The matches(in:options:range:) method returns an array of all matches. This is useful when you need to process every occurrence of the pattern.
let text = "Codes: ABC-123, DEF-456, GHI-789"let pattern = "[A-Z]{3}-\\\\d{3}"let regex = try NSRegularExpression(pattern: pattern, options: [])let range = NSRange(location: 0, length: text.utf16.count)let matches = regex.matches(in: tex