Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if its a mac address in kotlin

Tags:

kotlin

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"
like image 410
Morphinz Avatar asked Nov 07 '25 11:11

Morphinz


2 Answers

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")
        }
    }
}
like image 196
Михаил Нафталь Avatar answered Nov 09 '25 02:11

Михаил Нафталь


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)}")
    }
}
like image 26
Aplet123 Avatar answered Nov 09 '25 00:11

Aplet123



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!