问题
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
回答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})$
来源:https://stackoverflow.com/questions/24115303/max-length-for-email-validation-with-regular-expression