I m just learning regular expression matching using javascript, and have a doubt regarding the scenario described below.
I'm trying to validate email, with condition below:
Format should be
[email protected]
where
A) "xxx", "yyy" and "zzz" parts can take values only between lowercase a and z
B) The length of zzz, yyy and xxx parts are arbitrary (should be minimum one though)
Now I understand I can build the regex like this:
EDIT:
CORRECTED REG EXP
/[a-z]+@[a-z]+\.[a-z]+/
and the above would evaluate a string like "[email protected]" as true.
But my concern is, in the above expression if i provide "[email protected]"
, again it would evaluate as true. Now, if i modify the reg ex as **/[a-z]{1,}@[a-z]+\.[a-z]+/**
even then it would evaluate "[email protected]"
as true because of the presence of "a" as the first character.
So, I would like to know how to match the first part "xxx" in the email "[email protected]"
in a way that it checks the entire string from first char till it reaches the @ symbol with the condition that it should take only a to z as valid value.
In other words, the regex should not mind the length of the username part of email, and irrespective of the number of chars entered, it should test it based on the specified regex condition, and it should test it for the set of chars from index 1 to index of @.
To check the length of a string, a simple approach is to test against a regular expression that starts at the very beginning with a ^ and includes every character until the end by finishing with a $.
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.
Your regular expression will not show [email protected]
to be a match. It will, however, show that [email protected]
is a match. The regular expression markers you're missing are ^
for the start of string and $
for end of string. This is what you're looking for:
/^[a-z]{1,}@[a-z]+\.[a-z]+$/
You can test this expression out over on this online validator: http://tools.netshiftmedia.com/regexlibrary/#
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With