简体   繁体   English

正则表达式:验证大于0的数字(带或不带前导零)

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

Online demo 在线演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 不带前导零的数字的正则表达式 - Regular expression for numbers without leading zeros 正则表达式匹配带或不带前导零的小数 - Regular expression to match decimals with or without leading zeros 不带前导零的整数的正则表达式 - Regular expression for opposite of integer without leading zeros 如何编写正则表达式来匹配带或不带前导零的数字并排除带有特定文本的数字? - How do I write a regular expression to match numbers with or without leading zeros AND exclude numbers with certain text? 使用正则表达式替换命令在文件名字符串中的小于10的数字前插入前导零 - using regular expression substitution command to insert leading zeros in front of numbers less than 10 in a string of filenames 我使用什么正则表达式替换前导零? - What regular expression do I use for replacing numbers with leading zeros? 1-199(包括1和199)的正则表达式,不带前导零 - Regular expression for 1-199 (including both 1 and 199) without Leading zeros 使用正则表达式验证数字大于0且小于1999 - Regular expression to validate number greater than 0 and less than 1999 正则表达式(java)匹配数等于或大于20,以5递增,不允许前导零 - regex (java) match numbers equal or greater than 20, incremented by 5, no leading zeros allowed 正则表达式,用于读取前导零的正整数 - Regular expression for reading positive integers with leading zeros
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM