I'm trying to check a result is a mac-address in kotlin.
What is the proper way of using regex in if-else?
regex="%02X:%02X:%02X:%02X:%02X:%02X"
if $theresult is a mac address then do;
println"its a mac!"
else
println "its not a mac"
Solution using regex:
val macRegex = Regex("([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}")
fun isMac(str: String) = str.matches(macRegex)
fun main() {
val testCases = listOf(
"12:34:56:78:90:ab", // true
"24:1D:57:84:04:35", // true
"7B:2A:89:CF:9A:F3", // true
"12:34:56:78:90:AB", // true
"12:34:56:78:90:fg", // false
"12:34:56:78:90", // false
"1234567890ab" // false
)
testCases.forEach {
if (isMac(it)) {
println("$it - is a mac!")
} else {
println("$it - is not a mac")
}
}
}
You can split on colons and check to see if it has the right number of parts, then make sure each part is 2 characters of valid hex:
fun isLowerHex(chr: Char): Boolean =
chr >= '0' && chr <= '9' ||
chr >= 'a' && chr <= 'f'
fun isMac(str: String): Boolean {
val lowerStr = str.toLowerCase()
val parts = lowerStr.split(":")
return parts.size == 6 && parts.all { it.length == 2 && it.all(::isLowerHex) }
}
fun main() {
val testCases = listOf(
"12:34:56:78:90:ab", // true
"24:1D:57:84:04:35", // true
"7B:2A:89:CF:9A:F3", // true
"12:34:56:78:90:AB", // true
"12:34:56:78:90:fg", // false
"12:34:56:78:90", // false
"1234567890ab" // false
);
testCases.forEach {
println("$it ${isMac(it)}")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With