[英]How to check if regular expression matches the whole string?
我有一个正则表达式,可以匹配这样的东西:asdasd [text]; 一次只执行一次即可,但是如果有类似以下内容的话:
$badinput="add[2,5,525];print['peron'];print['asd','cgfg];time;print['iudofiusdoif'];"; #time should not be matched
这是现在的代码:
verify($badinput);
sub verify
{
#returns 1 if it's ok, or the text that breaks the match
my $inp = pop;
if ($inp =~ /^(?:\w{2,6}\[(?<!\\\[).*?\](?<!\\\]);)+$/s)
{
return 1;
}else{
return 0; #should be the text that breaks the match or the char number
};
}
无论第一个指令是否匹配,它都会返回1。 我该如何解决?
单程。 我的正则表达式与您的正则表达式相似,但没有后顾之忧。
一个例子。 script.pl
内容:
#! /usr/bin/perl
use warnings;
use strict;
while ( <DATA> ) {
chomp;
printf qq|%s ==> %s\n|, $_, ( m/^(\w{2,6}\[[^]]*\];)+$/ ) ? q|ok| : q|not ok|;
}
__DATA__
add[2,5,525];print['peron'];print['asd','cgfg];time;print['iudofiusdoif'];
add[2,5,525];print['peron'];print['asd','cgfg];print['iudofiusdoif'];
像这样运行:
perl script.pl
具有以下输出:
add[2,5,525];print['peron'];print['asd','cgfg];time;print['iudofiusdoif']; ==> not ok
add[2,5,525];print['peron'];print['asd','cgfg];print['iudofiusdoif']; ==> ok
sub verify
{
return ($_[0] =~ m/^((?:\w{2,6}\[[^\]]*\];)+)$/)? 1 : 0;
}
在此处测试此代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.