find ipv4 addresses in a string using regex in swift

To find IPv4 addresses in a string using regular expressions in Swift, we need to define a pattern that matches IPv4 addresses. The pattern should consist of four sets of digits separated by dots, where each set consists of 1-3 digits. Here's the regular expression pattern in Swift:

main.swift
let pattern = #"(\d{1,3}\.){3}\d{1,3}"#
40 chars
2 lines

Next, we use NSRegularExpression class to create a regular expression object from the pattern. Then we can use this object to search for matches in the input string.

main.swift
let input = "The server has IP address 192.168.0.1 and the client has 10.0.0.2"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
256 chars
4 lines

The matches array contains all the ranges in the input string that match the regex pattern. To extract the matched IPv4 addresses, we can use the substring(with:) method of the input string.

main.swift
for match in matches {
    let range = match.range
    let ipv4Address = (input as NSString).substring(with: range)
    print(ipv4Address)
}
141 chars
6 lines

This will print:

main.swift
192.168.0.1
10.0.0.2
21 chars
3 lines

Here's the complete code:

main.swift
let input = "The server has IP address 192.168.0.1 and the client has 10.0.0.2"
let pattern = #"(\d{1,3}\.){3}\d{1,3}"#

do {
    let regex = try NSRegularExpression(pattern: pattern, options: [])
    let matches = regex.matches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count))
    
    for match in matches {
        let range = match.range
        let ipv4Address = (input as NSString).substring(with: range)
        print(ipv4Address)
    }
} catch let error {
    print("regex error: \(error.localizedDescription)")
}
553 chars
16 lines

gistlibby LogSnag