find email addresses in a string using regex in swift

One way to find email addresses in a string using regular expressions in Swift is to define a regular expression pattern that matches the general format of an email address. The following code demonstrates how to do this:

main.swift
func findEmails(in string: String) -> [String] {
    let pattern = "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
    
    guard let regex = try? NSRegularExpression(pattern: pattern) else {
        return []
    }
    
    let range = NSRange(location: 0, length: string.utf16.count)
    let matches = regex.matches(in: string, range: range)
    
    return matches.map {
        guard let range = Range($0.range, in: string) else {
            return ""
        }
        return String(string[range])
    }
}
514 chars
18 lines

The findEmails function takes a string as input and returns an array of strings, containing all the email addresses found in the input string.

The regular expression pattern used is as follows:

main.swift
[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}
47 chars
2 lines

This pattern matches a sequence of characters that consists of one or more of the following:

  • Letters (A-Z, a-z)
  • Digits (0-9)
  • Special characters (._%+-)

Followed by the @ symbol, and then a sequence of letters, digits, and hyphens, followed by a dot and then two or more letters. This pattern should match the general format of an email address.

The guard let regex = try? NSRegularExpression(pattern: pattern) statement creates a regular expression object from the pattern, or returns an empty array if there was an error.

The let range = NSRange(location: 0, length: string.utf16.count) statement defines the range of the input string to search for email addresses.

The let matches = regex.matches(in: string, range: range) statement finds all the matches of the regular expression in the input string, within the specified range.

The function maps the matches to an array of strings, using the String(string[range]) statement to extract the matched email addresses from the input string.

Example usage:

main.swift
let string = "This is a test email@example.com and another test john.doe@example.com."
let emails = findEmails(in: string)
print(emails) // Output: ["email@example.com", "john.doe@example.com"]
194 chars
4 lines

gistlibby LogSnag