-1

我正在尝试为给定字符串(在特定接口中)允许的最大长度创建 Perl 验证表达式

我试过/.{0,5}/或者/^.{0,5}&/我注意到在许多类似的情况下使用过,但似乎任何输入的字符串(甚至低于 20 个字符)都失败了......

我已经搜索和测试了很多方法,但没有结果。

我最近尝试过:

[[:alpha:]]\{0,20\}

但是行为很奇怪……

我怎样才能解决这个问题?我只是想阻止用户在表单中输入 20 个或更多字符。

4

3 回答 3

3

length()尝试使用该函数,而不是使用正则表达式。

例子:

my $max = 4;
my $input = "qwerty";
if (length($input) < $max) {
    print "[$input] is less than $max\n";
} 
else {
    print "[$input] is more or equal than $max\n";
}

perldoc -f length
于 2013-02-07T15:51:49.337 回答
1

如果您正在从命令行读取输入,请尝试以下操作:

#!/usr/perl/bin -w

use strict;

my $input;
while (1) {
    $input = <>;
    if(length($input) < 20) {
        print "perfect\n";
    } 
    else {
        print "Exceeded 20 characters\n";
        exit(1);
    }
}
于 2013-02-08T11:05:25.060 回答
0

使用/^.{1,20}$/

$ echo "12345678901234567890123" | perl -nle "print if /^.{1,20}$/"

$ echo "12345678901234567890" | perl -nle "print if /^.{1,20}$/"
12345678901234567890
于 2013-02-07T16:53:19.010 回答