[英]Regular expression : validate numbers greater than 0, with or without leading zeros
I need a regular expression that will match strings like T001, T1, T012, T150 ---- T999. 我需要一个正则表达式来匹配T001,T1,T012,T150 ---- T999之类的字符串。
I made it like this : [tT][0-9]?[0-9]?[0-9]
, but obviously it will also match T0, T00 and T000, which I don't want to. 我是这样写的:
[tT][0-9]?[0-9]?[0-9]
,但显然它也可以匹配我不想使用的T0,T00和T000。
How can I force the last character to be 1 if the previous one or two are zeros ? 如果前一个或两个为零,如何强制最后一个字符为1?
I would not use regexp for that. 我不会为此使用regexp。
<?php
function tValue($str) {
if (intval(substr($str, 1)) !== 0) {
// T value is greater than 0
return $str;
} else {
// convert T<any number of 0> to T<any number-1 of 0>1
return $str[ (strlen($str) - 1) ] = '1';
}
}
// output: T150
echo tValue('T150'), PHP_EOL;
// output: T00001
echo tValue('T00000'), PHP_EOL;
// output: T1
echo tValue('T0'), PHP_EOL;
// output: T555
echo tValue('T555'), PHP_EOL;
Codepad: http://codepad.org/hqZpo8K9 键盘: http : //codepad.org/hqZpo8K9
Quite easy using a negative lookahead: ^[tT](?!0{1,3}$)[0-9]{1,3}$
使用否定的前瞻非常容易:
^[tT](?!0{1,3}$)[0-9]{1,3}$
Explanation 说明
^ # match begin of string
[tT] # match t or T
(?! # negative lookahead, check if there is no ...
0{1,3} # match 0, 00 or 000
$ # match end of string
) # end of lookahead
[0-9]{1,3} # match a digit one or three times
$ # match end of string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.