Search code examples
regexdigits

4 digit regex which maybe starts with 0


\b(0?[1-9]){4}

I have this Regex Which can find

1234 

But not

0123

It finds 01234 which is more than 4 digits

Which part of my Regex is wrong?


Solution

  • The problem with your regex is that you've specified ? for the 0 match, which means zero or one matches. Thus, you can match 5-digit strings (and larger ones) as a result.

    The problem is that ? contributes 0 or 1 and then your 1-9 test always contributes 1. You do a match 4 times, so you could match anything from a 4-digit to an 8-digit string.

    Here's a much simpler version, which you can test with https://regexr.com/.

    \b[0-9][1-9]{3}\b
    

    This tests for 0-9 in the first position, and then 1-9 in the next 3, just as required.

    Example Output

    yes: 1234
    yes: 0123
    no:  01234
    no:  12345
    no:  0001
    yes: 0125