简体   繁体   中英

Minimum and maximum length in a regular expression

I'm using the following regular expression to validate emails:

^\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$

Now I want to modify this regular expression to validate the email length using {5,100}. How can I do that?

^(?=.{5,100}$)\w+([-.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$

I'm using the zero-width lookahead. It won't consume characters, so you can then recheck them with your expression.

Be careful. This is a relatively weak expression and matches even user@server.com.net.org . Email regexes were already discussed in many other questions like this one .

Checking for the length of a string can generally be done within the language/tool you're using. This might be even faster in some cases. As an example (in Perl):

my $len = length $str;
if ($len < 5 || $len > 100) {
    # Something is wrong
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM