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.swift504 chars14 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