Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match an arbitrary length of characters in a string using javascript?

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 @.

like image 860
arun nair Avatar asked Nov 05 '11 16:11

arun nair


People also ask

How do I find the length of a string in regex?

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 $.

How do I match a character in regex?

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).

How do you match a character in JavaScript?

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.


1 Answers

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/#

like image 198
Joel Etherton Avatar answered Nov 03 '22 01:11

Joel Etherton