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
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
A combination of both attempts is probably what you need:
^[0-9]{1,45}$
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-9]{1,45}$
is correct.
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.
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}$