find ipv6 addresses in a string using regex in swift

To find IPv6 addresses in a string using regex in Swift, you can use the following code:

main.swift
func findIPv6(in string: String) -> [String] {
    let regexString   = "(([0-9a-fA-F]){1,4}:){7}([0-9a-fA-F]){1,4}"
    let regex = try! NSRegularExpression(pattern: regexString, options: [])
    
    let range = NSRange(location: 0, length: string.utf16.count)
    let results = regex.matches(in: string, options: [], range: range)
    
    return results.map {
        String(string[Range($0.range, in: string)!])
    }
}
424 chars
12 lines

Here, we define a function called findIPv6 that takes in a string as input and returns an array of strings containing all the IPv6 addresses found in the input string.

We define a regular expression pattern that matches an IPv6 address, using the (([0-9a-fA-F]){1,4}:){7}([0-9a-fA-F]){1,4} pattern.

We then create a regular expression object using the pattern and search for matches in the input string. We return an array of all the matches found, by converting the matches to strings using the String() constructor.

related categories

gistlibby LogSnag