regex pattern to validate email
To validate an email using a regular expression (regex) pattern in Kotlin, you can use the following pattern:
val pattern = Regex("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\$")
Let's break down the regex pattern and explain each step:
^
- The caret symbol
^
indicates the start of the line.
[A-Za-z0-9._%+-]+
- This part matches one or more occurrences of characters that can be letters (both uppercase and lowercase), digits, or any of the following special characters:
._%+-
.
@
- This matches the literal
@
symbol.
[A-Za-z0-9.-]+
- This part matches one or more occurrences of characters that can be letters (both uppercase and lowercase), digits, or any of the following special characters:
.-
.
\\.
- This matches the literal
.
symbol. Since.
is a special character in regex, we need to escape it with a backslash\
.
[A-Za-z]{2,}
- This part matches two or more occurrences of characters that can be letters (both uppercase and lowercase).
\
- The backslash
\
is used to escape the dollar sign$
, which is a special character in regex.
$
- The dollar sign
$
indicates the end of the line.
So, in summary, the regex pattern ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$
validates an email address by checking if it starts with one or more occurrences of letters, digits, and certain special characters, followed by an @
symbol, followed by one or more occurrences of letters, digits, and certain special characters, followed by a dot .
symbol, and ends with two or more occurrences of letters. This pattern ensures that the email address follows a common format.
To use this regex pattern in Kotlin, you can create a Regex
object like this:
val pattern = Regex("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\$")
You can then use this pattern to validate an email address by calling the matches
function on the pattern and passing in the email address as a string:
val email = "[email protected]"
val isValidEmail = pattern.matches(email)
The isValidEmail
variable will be true
if the email address is valid according to the regex pattern, and false
otherwise.