Chapters

Hide chapters

Swift Cookbook

Live Edition · Multiplatform · Swift · Editor agnostic

Use Regular Expressions in Swift
Written by Team Kodeco

In Swift, you can use regular expressions, also known as regex, to search and manipulate strings. A regular expression is a pattern that can match a set of strings.

Here’s how to use regular expressions in Swift:

import Foundation

let message = "Hello, World! My email address is example@example.com"

// You can use the range(of:options:range:locale:) method to find the range of a regular expression match in a string
let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
if let match = message.range(of: emailRegex, options: .regularExpression) {
  let email = message[match]
  print(email) // Output: "example@example.com"
}

You can also use the replaceMatches method to replace all occurrences of a regular expression with a new string.

let modifiedMessage = message.replacingOccurrences(of: emailRegex, with: "******", options: .regularExpression)
print(modifiedMessage) // Output: "Hello, World! My email address is ******"
© 2024 Kodeco Inc.