Regular Expressions in Swift: A Complete Guide for Beginners
Regular expressions (regex) are a powerful tool for searching, replacing, and validating text data. In Swift, working with regular expressions is implemented through the NSRegularExpression class from the Foundation framework. In this article, you will learn how to create and apply regular expressions in iOS and macOS applications, examine real-world examples, and master the basics of syntax.
1. Basics of Regular Expression Syntax
Before writing Swift code, it's important to understand the basic regex symbols and constructs. Here are the key elements:
.— any character (except newline)*— 0 or more repetitions of the previous character+— 1 or more repetitions?— 0 or 1 repetition (makes the previous character optional)\\d— any digit (0-9)\\w— any letter, digit, or underscore[abc]— one of the characters a, b, or c[^abc]— any character except a, b, c^— start of string$— end of string
These symbols are combined to create patterns. For example, the pattern ^[A-Za-z]+$ means: the string consists only of Latin alphabet letters from start to end.
2. Creating and Using NSRegularExpression in Swift
In Swift, working with regex starts by importing Foundation and creating an instance of NSRegularExpression. Let's look at a simple example: finding all digits in a string.
import Foundation
let text = "My number: 123-456-7890"let pattern = "\\\\d+" // pattern: one or more digits
do { let regex = try NSRegularExpression(pattern: pattern) let results = regex.matches(in: text, range: NSRange(text.startIndex..., in: text)) for match in results { if let range = Range(match.range, in: text) { print("Found: \\(text[range])") } }} catch { print("Error in regular expression: \\(error.localizedDescription)")}// Output:// Found: 123// Found: 456// Found: 7890Note the escaping of the backslash: in a Swift string, "\\\\d" corresponds to the regular expression \\d. The NSRegularExpression class throws an exception for an invalid pattern, so we use try-catch.
2.1. Working with NSRange
The matches(in:range:) method returns an array of NSTextCheckingResult objects. Each result contains the range (NSRange) of the found match. To convert to a Swift Range, use the initializer Range(match.range, in: text).
3. Practical Examples of Regular Expressions
Let's look at three typical tasks: email validation, URL extraction, and text replacement.
3.1. Email Address Validation
Let's check if a string matches a simple email pattern (simplified version):
func isValidEmail(_ email: String) -> Bool { let pattern = "^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Za-z]{2,}$" let regex = try? NSRegularExpression(pattern: pattern) let range = NSRange(location: 0, length: email.utf16.count) return regex?.firstMatch(in: email, range: range) != nil}
print(isValidEmail("test@example.com")) // trueprint(isValidEmail("invalid-email")) // falseHere we use firstMatch, which returns the first match. If there are no matches, it returns nil.
3.2. Extracting URLs from Text
Suppose we have a string with several links. Let's extract all URLs:
let text = "Visit the site https://pythonlib.ru or write to support@pythonlib.ru"let pattern = "https?://[\\\\w./%-]+"
do