This tutorial will show you how to solve HackerRank Valid Username Checker using Kotlin. In different web applications we define certain rules for choosing the username, such as, it should consists of maximum 30 characters; it should not have any special character; it may contain one or more digits; it must starts with a letter, etc. So here also we have some certain rules for choosing the username and we will check valid username regular expression in Kotlin language.
Please read here how to create Kotlin project in Eclipse.
You are updating the username policy on your company’s internal networking platform. According to the policy, a username is considered valid if all the following constraints are satisfied:
The username consists of 8 to 30 characters inclusive. If the username consists of less than 8 or greater than 30 characters, then it is an invalid username.
The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a-z], uppercase characters [A-Z], and digits [0-9].
The first character of the username must be an alphabetic character, i.e., either lowercase character [a-z] or uppercase character [A-Z].
For each of the usernames, the code prints true if the username is valid; otherwise false each on a new line.
Sample Input
Julia Samantha Samantha_21 1Samantha Samantha?10_2A JuliaZ007 Julia@007 _Julia007
Sample Output
false true true false false true false false
The source code
class ValidUsername { companion object { @JvmStatic val USER_NAME_REGEX = "^[A-Za-z][A-Za-z0-9_]{7,29}$" fun isValidUsername(userName: String): Boolean { return USER_NAME_REGEX.toRegex().matches(userName); } } } fun main(args: Array<String>) { println(ValidUsername.isValidUsername("Julia")); println(ValidUsername.isValidUsername("Samantha")); println(ValidUsername.isValidUsername("Samantha_21")); println(ValidUsername.isValidUsername("1Samantha")); println(ValidUsername.isValidUsername("Samantha?10_2A")); println(ValidUsername.isValidUsername("JuliaZ007")); println(ValidUsername.isValidUsername("Julia@007")); println(ValidUsername.isValidUsername("_Julia007")); }
Running the Kotlin program
Do right click on the above Kotlin class and select Run As -> Kotlin Application
Output
false true true false false true false false
Thanks for reading.