How to check if a string contains only letters, numbers, underscores and dashes in Kotlin

1 Answer

0 votes
fun isValidString(s: String): Boolean {
    val pattern = Regex("^[A-Za-z0-9_-]*$")
    
    return pattern.matches(s)
}

fun main() {
    val s1 = "-abc_123-"
    println(if (isValidString(s1)) "yes" else "no")

    val s2 = "-abc_123-(!)"
    println(if (isValidString(s2)) "yes" else "no")
}

 
  
/*
run:
  
yes
no
  
*/

 



answered May 31, 2025 by avibootz
...