find phone numbers in a string using regex in swift

To find phone numbers in a string using regular expressions (regex) in Swift, we can use the built-in NSRegularExpression class. Here's an example code snippet that demonstrates how to do this:

main.swift
let phoneNumberRegex = try? NSRegularExpression(pattern: "\\b\\d{3}[\\-]\\d{3}[\\-]\\d{4}\\b", options: [])
let text = "Hello, my phone number is 123-456-7890. Call me at home."

if let matches = phoneNumberRegex?.matches(in: text, options: [], range: NSRange(location: 0, length: text.utf16.count)) {
    let phoneNumbers = matches.map {
        String(text[Range($0.range, in: text)!])
    }
    
    print("Phone numbers found:")
    print(phoneNumbers)
} else {
    print("No phone numbers found")
}
504 chars
14 lines

In this example, we first define a regular expression \\b\\d{3}[\\-]\\d{3}[\\-]\\d{4}\\b, which matches phone numbers in the format xxx-xxx-xxxx, where x is a digit.

We then use NSRegularExpression to search for this pattern in the text string. The matches method returns an array of NSTextCheckingResult objects, which contain information about the location of the matching text within the original string.

We then use the map method to convert these NSTextCheckingResult objects to an array of phone number strings, extracted from the original text string using the Range object obtained from the range property of each NSTextCheckingResult.

Finally, we print out the array of phone numbers that were found, or a message indicating that no phone numbers were found.

gistlibby LogSnag