To check if a string contains only alphabets and numbers in Kotlin, you can use regular expressions.
In this example,
matches
function to check if the string matches the pattern.containsOnlyAlphabetsAndNumbers
to true
, otherwise false
.fun main() {
val str = "Hello123";
val pattern = Regex("^[a-zA-Z0-9]+");
val containsOnlyAlphabetsAndNumbers = pattern.matches(str);
println("String contains only alphabets and numbers: $containsOnlyAlphabetsAndNumbers");
}
String contains only alphabets and numbers: true
In this tutorial, we learned How to Check if String contains only Alphabets and Numbers in Kotlin language with well detailed examples.