我正在尝试创建一个reg ex模式来匹配一个字符串,该字符串至少有一个数字,并且在可选的小数点之前最多有两个数字,如果包含小数点,则它们应该至少在它之后最多一到三位数字。
例如,应验证以下值。
0
0.0
0.00
0.000
00
00.0
00.00
00.000
以下值不应验证。
0.
00.
0.0000
00.0000
这是我到目前为止的代码
function check($string){
if(preg_match('/^[0-9][0-9]?(?:.[0-9]{1,3})$/', $string)){
return true;
} else {
return false;
}
}
您可以使用此正则表达式
^[0-9]{1,2}(?:.[0-9]{1,3})?$
组号d
的同义词
^d{1,2}(?:.d{1,3})?$
您可以使用更简单的正则表达式。
<?php
$tests = [ '0',
'0.0',
'0.00',
'0.000',
'00',
'00.0',
'00.00',
'00.000',
'0.',
'00.',
'0.0000',
'00.0000'
];
$regex_pattern = '/^d{1,2}(.d{1,3})?$/';
foreach($tests as $each_test){
echo $each_test," -----------> ",var_dump(1 === preg_match($regex_pattern,$each_test)),"<br/>";
}
输出:
0 -----------> bool(true)
0.0 -----------> bool(true)
0.00 -----------> bool(true)
0.000 -----------> bool(true)
00 -----------> bool(true)
00.0 -----------> bool(true)
00.00 -----------> bool(true)
00.000 -----------> bool(true)
0. -----------> bool(false)
00. -----------> bool(false)
0.0000 -----------> bool(false)
00.0000 -----------> bool(false)
'/^d{1,2}(.d{1,2})?$/'
正是您要搜索的模式。
但是很多时候,编写一个函数来保持整洁和简单是件好事,以防您想扩展这个想法
function OptionalDecimal($numstr) {
//use string count to check for the times decimal points appears in the string
if (substr_count($numstr,".") == 0) {
if(preg_match('/^d{1,2}$/', $numstr)) return 'true';
}
if (substr_count($numstr,".") == 1) {
if(preg_match('/^d{1,2}.d{1,2}$/', $numstr)) return 'true';
}
return 'false';
}
echo OptionalDecimal("4.7");
此函数执行相同的操作