Regex allow a string to only contain numbers 0 - 9 and limit length to 45

后端 未结 8 677
轮回少年
轮回少年 2020-12-02 13:57

I am trying to create a regex to have a string only contain 0-9 as the characters and it must be at least 1 char in length and no more than 45. so

8条回答
  •  有刺的猬
    2020-12-02 14:58

    You are almost there, all you need is start anchor (^) and end anchor ($):

    ^[0-9]{1,45}$
    

    \d is short for the character class [0-9]. You can use that as:

    ^\d{1,45}$
    

    The anchors force the pattern to match entire input, not just a part of it.


    Your regex [0-9]{1,45} looks for 1 to 45 digits, so string like foo1 also get matched as it contains 1.

    ^[0-9]{1,45} looks for 1 to 45 digits but these digits must be at the beginning of the input. It matches 123 but also 123foo

    [0-9]{1,45}$ looks for 1 to 45 digits but these digits must be at the end of the input. It matches 123 but also foo123

    ^[0-9]{1,45}$ looks for 1 to 45 digits but these digits must be both at the start and at the end of the input, effectively it should be entire input.

提交回复
热议问题