find mac addresses in a string using regex in swift

You can use a regular expression to extract the MAC addresses from a string in Swift. Here's some code to get you started:

main.swift
func extractMACAddresses(from input: String) -> [String] {
    let regex = try! NSRegularExpression(pattern: "([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})")
    let matches = regex.matches(in: input, range: NSRange(input.startIndex..., in: input))
    return matches.map {
        String(input[Range($0.range, in: input)!])
    }
}
327 chars
8 lines

This function takes in a string input, which may contain one or more MAC addresses. It creates a regular expression that matches the typical MAC address format, with six groups of two hexadecimal digits separated either by colons or hyphens. The NSRange is used to specify the range of the input string which we want to search for the pattern.

The matches variable is an array of all the matches (i.e. MAC addresses) found in the input string. Finally, we use map to convert the matches from NSTextCheckingResult objects to strings.

Here's an example usage of the function:

main.swift
let input = "Here are some MAC addresses: 01:23:45:67:89:ab and 12-34-56-78-9a-bc"
let macAddresses = extractMACAddresses(from: input)
print(macAddresses) // ["01:23:45:67:89:ab", "12-34-56-78-9a-bc"]
201 chars
4 lines

Note that this code assumes that the MAC addresses in the input string are valid and properly formatted. If there is any possibility that the input may contain other strings that look like MAC addresses but are not valid, you may need to add additional validation to ensure that only valid MAC addresses are returned.

gistlibby LogSnag