[英]Regular expression : validate numbers greater than 0, with or without leading zeros
我需要一個正則表達式來匹配T001,T1,T012,T150 ---- T999之類的字符串。
我是這樣寫的: [tT][0-9]?[0-9]?[0-9]
,但顯然它也可以匹配我不想使用的T0,T00和T000。
如果前一個或兩個為零,如何強制最后一個字符為1?
我不會為此使用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;
鍵盤: http : //codepad.org/hqZpo8K9
使用否定的前瞻非常容易: ^[tT](?!0{1,3}$)[0-9]{1,3}$
說明
^ # 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.