Regex for Email Validation in Kotlin
val emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\$".toRegex()
fun isEmailValid(email: String): Boolean {
return emailRegex.matches(email)
}
- Explanation:
val emailRegex = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\$".toRegex()
: This line defines the regular expression pattern for validating an email address. It uses the toRegex()
function to create a regex object from the specified pattern.fun isEmailValid(email: String): Boolean { ... }
: This function takes an email address as input and returns a boolean value indicating whether the email is valid or not.return emailRegex.matches(email)
: The function uses the matches
function of the regex object to check if the input email matches the defined pattern, and returns the result as a boolean value.