Introduction to Regular Expressions in Swift
\n\nRegular expressions (regex) are a powerful tool for searching, extracting, and replacing text based on patterns. In Swift, working with regular expressions is implemented through the NSRegularExpression class from the Foundation framework, as well as through built-in string methods. This is an indispensable tool when developing iOS and macOS applications for form validation, data parsing, text filtering, and many other tasks.
In this article, we will explore the main capabilities of working with regular expressions in Swift using practical examples. You will learn how to create patterns, perform search, replace, and data extraction.
\n\nBasics of Working with NSRegularExpression
\n\nThe NSRegularExpression class is the primary way to work with regular expressions in Swift. Let's look at basic operations.
Creating a Regular Expression
\n\nimport Foundation\n\nlet pattern = "[A-Za-z]+@[A-Za-z]+\\\\.[A-Za-z]+"\nguard let regex = try? NSRegularExpression(pattern: pattern) else {\n fatalError("Invalid pattern")\n}\n\nNote the double backslash \\\\ — in Swift strings, the backslash needs to be escaped.
Finding the First Match
\n\nlet text = "Contact us by email: support@example.com"\nlet nsString = text as NSString\nlet range = NSRange(location: 0, length: nsString.length)\n\nif let match = regex.firstMatch(in: text, range: range) {\n let email = nsString.substring(with: match.range)\n print("Found email: \\(email)") // support@example.com\n}\n\nFinding All Matches
\n\nlet text = "Contacts: info@site.com, admin@site.com, support@site.com"\nlet matches = regex.matches(in: text, range: NSRange(location: 0, length: text.count))\n\nfor match in matches {\n let range = match.range\n let email = (text as NSString).substring(with: range)\n print(email)\n}\n// Output:\n// info@site.com\n// admin@site.com\n// support@site.com\n\nUsing Capture Groups
\n\nCapture groups allow you to extract parts of a match. In Swift, groups are denoted by parentheses ().
Extracting Data Using Groups
\n\nlet pattern = "(\\\\d{4})-(\\\\d{2})-(\\\\d{2})"\nlet dateString = "Today: 2024-03-15"\n\nguard let regex = try? NSRegularExpression(pattern: pattern) else { return }\nlet nsString = dateString as NSString\n\nif let match = regex.firstMatch(in: dateString, range: NSRange(location: 0, length: nsString.length)) {\n let fullDate = nsString.substring(with: match.range) // 2024-03-15\n let year = nsString.substring(with: match.range(at: 1)) // 2024\n let month = nsString.substring(with: match.range(at: 2)) // 03\n let day = nsString.substring(with: match.range(at: 3)) // 15\n \n print("Year: \\(year), Month: \\(month), Day: \\(day)")\n}\n\nNamed Groups (Working with Range)
\n\nStarting with Swift 5.7, you can use a more convenient syntax with Range:
let text = "Price: 1500 rubles"\nlet pattern = #"(\\d+)\\srubles"#\n\nif let range = text.range(of: pattern, options: .regularExpression) {\n let match = text[range]\n print("Found: \\(match)") // 1500 rubles\n}\n\nText Replacement Using Regular Expressions
\n\nOne of the most useful features is replacing parts of text based on a pattern.
\n\nSimple Replacement
\n\nlet text = "Call the number +7 (123) 456-78-90"\nlet pattern = "\\\\+7\\\\s\\\\(\\\\d{3}\\\\)\\\\s\\\\d{3}-\\\\d{2}-\\\\d{2}"\nlet replacement = "[number hidden]"\n\nguard let regex = try? NSRegularExpression(pattern: pattern) else { return }\nlet modifiedText = regex.stringByReplacingMatches(\n in: text,\n range: NSRange(location: 0, length: text.count),\n withTemplate: replacement\n)\n\nprint(modifiedText) // Call the number [number hidden]\n\n