GardenMobile & interfaces

Reading a Wi-Fi QR payload with a Kotlin regex

A restricted WIFI payload parser and the capture groups used to read its fields.

A regular expression can extract fields from a narrowly defined QR payload. This older Kotlin snippet expects the SSID, authentication type, and password in a fixed order:

var wifiPattern = "(WIFI:S:)(.{1,32})(;T:)(WPA|WEP)(;P:)(.{1,32})(;;)".toRegex()
if (wifiPattern.matches(value)){}

// Parse
val infoArr = wifiPattern.find(value)?.groups
if (!infoArr.isNullOrEmpty() && infoArr.size == 8) {
    val ssid = infoArr[2]
    val password = infoArr[6]
    val type = infoArr[4]
} 

Read the capture groups

The pattern has seven capture groups, plus the complete match at index zero. The code reads the SSID from group 2, authentication type from group 4, and password from group 6. The literal separators occupy the other groups.

The matches call tests the complete input, while the subsequent find retrieves a matching segment. Decide deliberately whether accepting only a whole payload is required before using the extracted fields.

Keep the scope visible

This pattern requires nonempty values of bounded length and accepts only the two listed authentication labels. It does not implement a complete Wi-Fi QR grammar or handle escaped delimiters generally. The snippet is preserved as a regex exercise, not presented as a validated parser for every network credential.

← Back to the garden