A regular expression allows a string to contain only digits 0-9 and limit the length to 45

I am trying to create a regular expression so that the string contains only 0-9 as characters, and it should be at least 1 char in length and no more than 45 . so the example will be 00303039 will be a coincidence, but 039330a29 will not.

So far this is what I have, but I'm not sure if this is correct.

 [0-9]{1,45} 

I also tried

 ^[0-9]{45}*$ 

but it doesn’t work either. I am not very familiar with regex, so any help would be great. Thank!

+41
string string-matching regex
Oct 19 '10 at 11:58
source share
7 answers

You are almost there, all you need is a binding ( ^ ) and the end of the binding ( $ ):

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

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

 ^\d{1,45}$ 

Anchors force the pattern to match entire inputs, not just parts of it.




Your regular expression [0-9]{1,45} looks for 1 to 45 digits, so a line like foo1 will also match, since it contains 1 .

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

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

^[0-9]{1,45}$ looking for 1 to 45 digits, but these digits should be both at the beginning and at the end of the input, so it must be an integer .

+126
Oct 19 '10 at 12:00
source share

The first match with any number of digits inside your string (also accepts other characters, ie "039330a29"). The second allows only 45 digits (and no less). So just grab the best of both:

 ^\d{1,45}$ 

where \d matches [0-9] .

+14
Oct 19 '10 at 12:00
source share

Use this regex if you don't want to start from scratch:

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

If you do not mind starting from scratch, use:

 ^[0-9]{1,45}$ 
+9
Jul 11 '13 at 8:14
source share

codaddict provided the correct answer. As for what you tried, I will explain why they do not cut:

  • [0-9]{1,45} almost exists, however, it corresponds to a line from 1 to 45 digits, even if it appears in another longer line containing other characters. Therefore, you need ^ and $ to limit it to exact match.

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

+5
Oct 19 2018-10-19
source share

The combination of both attempts is probably what you need:

 ^[0-9]{1,45}$ 
+3
Oct 19 '10 at 12:01
source share

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

+2
Oct 19 '10 at 12:00
source share

Rails doesn't like using ^ and $ for some security reasons, it might be better to use \ A and \ z to set the beginning and end of a line

+2
Apr 05 '14 at 13:25
source share



All Articles