Max length for email validation with regular expression

我的未来我决定 提交于 2019-12-23 18:13:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!