Search code examples
regexregex-group

Regex to not allow duplicate wild cards


I want to make regex which can pass the following cases:

02:12
10:23
00.23
0.23
.02
:88

Here is what i have tried: ^([0-9:. ])*[.: ]+$

But it allows duplicate" :, ., (space)", and also I'm not able to limit to 1-2 digits on both sides of wildcards. Any help would be great. Thanks


Solution

  • The pattern you tried only matches digits on the left side and matching the duplicates is due to the quantifiers.

    If you want to allow 1 or 2 digits on both sides and make the digits on the left optional:

    ^[0-9]{0,2}[.:][0-9]{1,2}$
    
    • ^ Start of string
    • [0-9]{0,2} Match 0, 1 or 2 times a digit 0-9
    • [.:] Match either . or :
    • [0-9]{1,2} Match 1 or 2 times a digit 0-9
    • $ End of string

    Regex demo