正则表达式最小和最大长度

时间:2022-09-28 23:09:17

I'm using the following regular expression to validade emails

我正在使用以下正则表达式来验证电子邮件

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

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

现在我想修改这个正则表达式以使用{5,100}来验证电子邮件的长度,我该怎么做?

Thank you.

谢谢。

2 个解决方案

#1


2  

^(?=.{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.

我正在使用零宽度前瞻。它不会消耗字符,因此您可以使用表达式重新检查它们。

#2


1  

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

小心。这是一个相对较弱的表达,甚至匹配user@server.com.net.org。在这样的许多其他问题中已经讨论了电子邮件正则表达式。

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

检查字符串的长度通常可以在您使用的语言/工具中完成。在某些情况下,这可能会更快。作为一个例子(在Perl中):

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

#1


2  

^(?=.{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.

我正在使用零宽度前瞻。它不会消耗字符,因此您可以使用表达式重新检查它们。

#2


1  

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

小心。这是一个相对较弱的表达,甚至匹配user@server.com.net.org。在这样的许多其他问题中已经讨论了电子邮件正则表达式。

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

检查字符串的长度通常可以在您使用的语言/工具中完成。在某些情况下,这可能会更快。作为一个例子(在Perl中):

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