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

NewToRegEx picture NewToRegEx · Oct 19, 2010 · Viewed 247.5k times · Source

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 example would be 00303039 would be a match, and 039330a29 would not.

So far this is what I have but I am not sure that it is correct

[0-9]{1,45} 

I have also tried

^[0-9]{45}*$

but that does not seem to work either. I am not very familiar with regex so any help would be great. Thanks!

Answer

codaddict picture codaddict · Oct 19, 2010

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.