我想检查一个数字是否在数字的末尾出现一定数量的时间,比如2次。正则表达式应该可以说类似于“group [0-9]在结尾处2次”,并且我可以在正则表达式中插入一个PHP变量,指示“重复量”,替换为2.检查数字结尾的任何数字的重复?
什么正则表达式我应该使用吗?
P.S:希望这个片段的PHP code可以帮助验证,如果表达式中,如果任何数字被以数字的末尾重复时间,这应该检查,是正确的。
$Regex="/$[help]$/";
$Input=array(123456,112345,333333,123455,99);
$CorrectOutput=array(0,0,0,1,1);
echo "==WORKING IN EVERY TEST CASE?==<br>";
for($TestEntry=0;$TestEntry<=4;$TestEntry++){
$Result = preg_match($Regex,$Input[$TestEntry]);
if($Result==$CorrectOutput[$TestEntry]){
echo "Got ".$Result.", expected ".$CorrectOutput[$TestEntry]." - Good, seems to be working for " . $Input[$TestEntry] . ".<br>";
}else{
echo "Got ".$Result.", expected ".$CorrectOutput[$TestEntry]." - Sorry, not working for " . $Input[$TestEntry] . ".<br>";
}
}
在此先感谢!
答案很可能是以下,非常感谢:
$Repetition = 3; //Number of times a digit repeats at the end of the number (min. 2)
$Regex='/(?:^(\d)\1{'.($Repetition-1).'}$)|(?:^.*(\d)(?!\2{'.$Repetition.'})(\d)\3{'.($Repetition-1).'}$)/';
哇,当然看起来令人印象深刻!我仍然得到“对不起,123455工作。”和“对不起,不适用于99”。但是,嗯.. – Chris 2011-12-17 13:46:12
这是因为你测试的网站在“和\,我在我自己的机器上运行这个代码使用PHP CLI得到正确的答案,你应该改变”到“上(例如'$ Regex ='/(^ |。)(^ |(!!\\ 1))(。)\\ 3 $ /';'on the that that you will get all 5 correct too :)网站。) – 2011-12-17 13:53:10
不知道你是如何发现的,但你是对的!现在工作很好,非常感谢! – Chris 2011-12-17 13:57:40