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

后端 未结 8 678
轮回少年
轮回少年 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:33

    Rails doesnt like the using of ^ and $ for some security reasons , probably its better to use \A and \z to set the beginning and the end of the string

    0 讨论(0)
  • 2020-12-02 14:35

    A combination of both attempts is probably what you need:

    ^[0-9]{1,45}$
    
    0 讨论(0)
  • 2020-12-02 14:37

    codaddict has provided the right answer. As for what you've tried, I'll explain why they don't make the cut:

    • [0-9]{1,45} is almost there, however it matches a 1-to-45-digit string even if it occurs within another longer string containing other characters. Hence you need ^ and $ to restrict it to an exact match.

    • ^[0-9]{45}*$ matches an exactly-45-digit string, repeated 0 or any number of times (*). That means the length of the string can only be 0 or a multiple of 45 (90, 135, 180...).

    0 讨论(0)
  • 2020-12-02 14:41

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

    0 讨论(0)
  • 2020-12-02 14:42

    For this case word boundary (\b) can also be used instead of start anchor (^) and end anchor ($):

    \b\d{1,45}\b
    

    \b is a position between \w and \W (non-word char), or at the beginning or end of a string.

    0 讨论(0)
  • 2020-12-02 14:52

    Use this regular expression if you don't want to start with zero:

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

    If you don't mind starting with zero, use:

    ^[0-9]{1,45}$
    
    0 讨论(0)
提交回复
热议问题