3

I find this regular expression for email validation.

[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})

I want max length for email will be 20 character so i change it to :

([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})){0,20}

but when i entered more than 20 characters,it accept! also I used

^([_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})){0,20}$ 

but it didn t work correctly.I want to use it in java code

anubhava
  • 761,203
  • 64
  • 569
  • 643
John
  • 115
  • 2
  • 3
  • 10
  • When you're doing `{0,20}` it means that the previous expression can repeat any number of times between zero to twenty. It does NOT restrict length. The simplest thing to do is to validate the length separately by adding a check for `String.length()` – Nir Alfasi Jun 09 '14 at 07:13

1 Answers1

1

You cannot just add {0,20} to the whole regex as it will mean from 0 to 20 occurrence of each email address.

You can use it like this using lookahead to enforce length:

^(?=.{1,20}$)[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$
anubhava
  • 761,203
  • 64
  • 569
  • 643