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.swift514 chars18 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.swift47 chars2 lines
This pattern matches a sequence of characters that consists of one or more of the following:
A-Z
, a-z
)0-9
)._%+-
)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.swift194 chars4 lines
gistlibby LogSnag