Regular expression : validate numbers greater than 0, with or without leading zeros

StackOverflow https://stackoverflow.com/questions/18227042

  •  24-06-2022
  •  | 
  •  

Вопрос

I need a regular expression that will match strings like 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.

How can I force the last character to be 1 if the previous one or two are zeros ?

Это было полезно?

Решение

Quite easy using a negative lookahead: ^[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

Другие советы

I would not use regexp for that.

<?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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top