swiftregexswift5.7swift-regexbuilder

How to use Swift 5.7 RegexBuilder to find a word after a sentence


I get a report from networksetup -listnetworkserviceorder terminal command for all networks services. The returned text is like this:

An asterisk (*) denotes that a network service is disabled.
(1) Ethernet
(Hardware Port: Ethernet, Device: en0)

(2) Wi-Fi
(Hardware Port: Wi-Fi, Device: en1)

(3) iPhone USB
(Hardware Port: iPhone USB, Device: en6)

(4) Thunderbolt Bridge
(Hardware Port: Thunderbolt Bridge, Device: bridge0)

(5) VPN (VPN2)
(Hardware Port: L2TP, Device: )

I'm trying to find device for Wi-Fi (en1) with RegexBuilder


        let search = Regex {
            "Hardware Port: Wi-Fi, Device: "
            Capture {
                OneOrMore(.word)
            }
        }

        if let result = try? search.wholeMatch(in: info) {
            print("Device: \(result.1)")
        }

This only works if the Hardware Port: Wi-Fi, Device: string is at the beginning of the text. If there are one or more characters before the above sentence the result would be nil

I've tried with this syntax and the result was the same (nil)

        let search = /Hardware Port: Wi-Fi, Device: (\w+)/

Solution

  • Just replace .wholeMatch with .firstMatch.

    As the name suggests .wholeMatch affects the whole string corresponding to a pattern literal with leading "^" and trailing "$"