[英]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.